c++流的异常捕获

在 C++ 中,当使用流(如 std::ifstreamstd::ofstream)时,常见的异常可以使用以下类型的异常捕获:

  1. std::ios_base::failure
    • 用于捕获与流操作相关的错误,例如打开文件失败、读写错误等。
  2. std::exception
    • 作为基类,可以捕获所有标准异常,适合处理未具体指定的流错误。
c++ 复制代码
#include <iostream>
#include <fstream>
#include <exception>

int main() {
    try {
        std::ifstream file("nonexistent.txt");
        if (!file) {
            throw std::ios_base::failure("Failed to open file");
        }
        // 进行读操作
    } catch (const std::ios_base::failure& e) {
        std::cerr << "Stream error: " << e.what() << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "General exception: " << e.what() << std::endl;
    }
    return 0;
}
相关推荐
小邓儿◑.◑4 小时前
C++武功秘籍 | 入门知识点
开发语言·c++
杨筱毅6 小时前
【优秀三方库研读】【C++基础知识】odygrd/quill -- 折叠表达式
c++·三方库研读
hjjdebug7 小时前
c++中的enum变量 和 constexpr说明符
c++·enum·constexpr
CoderCodingNo8 小时前
【GESP】C++二级真题 luogu-B4259 [GESP202503 二级] 等差矩阵
java·c++·矩阵
明月看潮生8 小时前
青少年编程与数学 02-018 C++数据结构与算法 11课题、分治
c++·算法·青少年编程·编程与数学
Echo``8 小时前
2:QT联合HALCON编程—图像显示放大缩小
开发语言·c++·图像处理·qt·算法
想睡hhh10 小时前
c++STL——stack、queue、priority_queue的模拟实现
开发语言·c++·stl
cloues break.10 小时前
C++初阶----模板初阶
java·开发语言·c++
wwww.wwww10 小时前
Qt软件开发-摄像头检测使用软件V1.1
开发语言·c++·qt
共享家952710 小时前
栈相关算法题解题思路与代码实现分享
c++·leetcode