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;
}
相关推荐
MSTcheng.5 分钟前
【C++】C++11新特性(二)
java·开发语言·c++·c++11
愚者游世8 分钟前
Delegating Constructor(委托构造函数)各版本异同
开发语言·c++·程序人生·面试·改行学it
小镇敲码人10 分钟前
探索华为CANN框架中的ACL仓库
c++·python·华为·acl·cann
liu****43 分钟前
2.深入浅出理解虚拟化与容器化(含Docker实操全解析)
运维·c++·docker·容器·虚拟化技术
A9better1 小时前
C++——不一样的I/O工具与名称空间
开发语言·c++·学习
王老师青少年编程1 小时前
2024年信奥赛C++提高组csp-s初赛真题及答案解析(阅读程序第2题)
c++·题解·真题·初赛·信奥赛·csp-s·提高组
MSTcheng.1 小时前
【C++】C++11新特性(三)
开发语言·c++·c++11
田野追逐星光2 小时前
STL容器list的模拟实现
开发语言·c++·list
StandbyTime2 小时前
《算法笔记》学习记录-第二章 C/C++快速入门
c++·算法笔记
我在人间贩卖青春2 小时前
C++之结构体与类
c++··结构体