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;
}
相关推荐
River4163 小时前
Javer 学 c++(十三):引用篇
c++·后端
感哥6 小时前
C++ std::set
c++
侃侃_天下6 小时前
最终的信号类
开发语言·c++·算法
博笙困了6 小时前
AcWing学习——差分
c++·算法
青草地溪水旁7 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁7 小时前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥7 小时前
C++ std::vector
c++
zl_dfq7 小时前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++
每天回答3个问题7 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
凯子坚持 c7 小时前
精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
c++·redis·list