【发布时间】:2016-02-29 18:10:11
【问题描述】:
我试图捕获从 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
但我希望代码能够捕获异常并显示错误消息。为什么它没有捕获异常?
【问题讨论】:
-
哪个编译器版本?在这里工作正常。
-
@Christian Hackl g++ vresion 5.3.0
-
@Msegade 这是GCC bug。
标签: c++ exception exception-handling fstream