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;
}
相关推荐
感哥3 小时前
C++ STL 常用算法
c++
saltymilk14 小时前
C++ 模板参数推导问题小记(模板类的模板构造函数)
c++·模板元编程
感哥14 小时前
C++ lambda 匿名函数
c++
沐怡旸20 小时前
【底层机制】std::unique_ptr 解决的痛点?是什么?如何实现?怎么正确使用?
c++·面试
感哥21 小时前
C++ 内存管理
c++
博笙困了1 天前
AcWing学习——双指针算法
c++·算法
感哥1 天前
C++ 指针和引用
c++
感哥2 天前
C++ 多态
c++
沐怡旸2 天前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4162 天前
Javer 学 c++(十三):引用篇
c++·后端