c++ - 在 main 中捕获 ifstream 异常

标签 c++ exception fstream

我试图捕获从 main 的类方法中读取文件时发生错误时引发的异常。简化后的代码是这样的:

#include <iostream>
#include <fstream>
#include <string>

class A
{
public:
    A(const std::string filename)
    {
       std::ifstream file;
       file.exceptions( std::ifstream::failbit | std::ifstream::badbit);
       file.open(filename);
    }

};

int main()
{
    std::string filename("file.txt");
    try
    {
        A MyClass(filename);
    }
    catch (std::ifstream::failure e)
    {
        std::cerr << "Error reading file" << std::endl;
    }

}

我编译此代码:

 $ g++ -std=c++11 main.cpp

如果 file.txt 存在,则不会发生任何事情,但如果不存在,程序将终止并出现以下错误:

terminate called after throwing an instance of 'std::ios_base::failure'
    what(): basic_ios::clear
zsh: abort (core dumped) ./a.out

但我希望代码能够捕获异常并显示错误消息。为什么没有捕获异常?

最佳答案

您可以通过在命令行中添加 -D_GLIBCXX_USE_CXX11_ABI=0 来使其在 GCC 中工作。 Here是 GCC 的一个工作示例。

从下面的评论(尤其是 LogicStuff 的测试)和我自己的测试看来,在 clang 和 MSVC 中它不会产生此错误。

感谢 LogicStuff 上面的评论,我们现在知道这是一个 GCC bug 。因为在 GCC C++03 中 ios::failure 不是从 runtime_error 派生的,所以没有被捕获。

另一个选择可能是更改为:

try
{
    A MyClass(filename);
}
catch (std::ifstream::failure e)
{
    std::cerr << "Error reading file\n";
}
catch (...)
{
    std::cerr << "Some other error\n";
}

关于c++ - 在 main 中捕获 ifstream 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35706496/

相关文章:

C++ 概念 - 我可以有一个要求类中存在函数的约束吗?

C++高内存和CPU

c++ - 使用 Linux 在 C++ 中的套接字服务器中使用 "Listen"

c++ - 在 C++ 中处理几乎所有的异常

exception - Yii完整性约束异常处理和用户友好消息

c++ - C++03 throw() 说明符 C++11 noexcept 之间的区别

c++ - 为什么我的代码不写入输出文件?

c++ - Fstream _Fgetc 访问冲突

c++ - gcc9 和 lcov 的覆盖范围

c++ - 使用 SFML 和 C++ 将像素打印到屏幕上