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;
}
相关推荐
宇宙超级无敌暴龙战士2 小时前
旮旯c语言三个任务
c++·c
BanyeBirth3 小时前
C++差分数组(二维)
开发语言·c++·算法
Fcy6483 小时前
C++ map和multimap的使用
开发语言·c++·stl
CC.GG3 小时前
【C++】STL容器----unordered_map和unordered_set的使用
java·数据库·c++
lengjingzju4 小时前
基于IMake的 GCC 编译与链接选项深度解析:构建高效、安全、可调试的现代软件
c++·安全·性能优化·软件构建·开源软件
xu_yule4 小时前
算法基础(数论)—算法基本定理
c++·算法·算数基本定理
CoderCodingNo5 小时前
【GESP】C++五级真题(结构体排序考点) luogu-B3968 [GESP202403 五级] 成绩排序
开发语言·c++·算法
星轨初途7 小时前
郑州轻工业大学2025天梯赛解题
c++·经验分享·笔记·算法·链表·剪枝
点云SLAM8 小时前
C++ 引用折叠(Reference Collapsing)和示例讲解说明
数据结构·c++·标准算法·完美转发·代码性能优化·c++ 引用折叠·typedef / using
chenyuhao20248 小时前
Linux网络编程:HTTP协议
linux·服务器·网络·c++·后端·http·https