我试图捕获从main读取类方法中的文件时发生错误时引发的异常。简化的代码是这样的:主要捕获ifstream异常
#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
但我希望代码捕获异常并显示错误消息。为什么它没有捕捉到异常?
哪个编译器版本?在这里工作很好。 –
@Christian Hackl g ++ vresion 5.3.0 – Msegade
@Msegade这是一个[GCC bug](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145)。 – LogicStuff