我试图捕获从 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/