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;
}
相关推荐
郝学胜_神的一滴16 小时前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境3 天前
C++ 的Eigen 库全解析
c++
卷无止境3 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴3 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18005 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴5 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨5 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint45610 天前
C++进阶(1)——前景提要
c++
夜悊10 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴10 天前
CMake 021: IF 条件判据详诠
c++·cmake