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;
}
相关推荐
Lazionr22 分钟前
多态:从多种形态到运行时绑定
开发语言·c++
别动我齐刘海33 分钟前
ROS2 Jazzy + C++ 实战路线——ros2_control
c++·人工智能·python·opencv·机器学习·机器人·github
All for pursuit.1 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
码匠许师傅1 小时前
【C++三方组件】glog:Google 出品的 C++ 日志库
c++
Lazionr1 小时前
二叉搜索树:从树形结构到高效查找
开发语言·c++
此生决int1 小时前
深入理解C++系列(21)——异常
开发语言·c++
曼巴UE51 小时前
UE5 客户端 需要的网络同步概念总结(3 )-事件同步 RPC 以及三种调用方式
网络·c++·网络协议·学习·rpc·ue5
All for pursuit.1 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
01二进制代码漫游日记2 小时前
C++之类和对象(上)02
c++
渡我白衣2 小时前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe