在main中捕获ifstream异常 [英] Catching ifstream exception in main
问题描述
我试图捕获在从main读取类方法中的文件时发生错误时引发的异常。简化的代码是这样的:
#include< iostream>
#include< fstream>
#include< string>
A类
{
public:
A(const std :: string filename)
{
std :: ifstream file;
file.exceptions(std :: ifstream :: failbit | std :: ifstream :: badbit);
file.open(文件名);
}
};
int main()
{
std :: string filename( file.txt);
试试
{
MyClass(filename);
}
捕获(std :: ifstream :: failure e)
{
std :: cerr<< 读取文件时出错<< std :: endl;
}
}
我用以下代码编译此代码: / p>
$ g ++ -std = c ++ 11 main.cpp
如果file.txt存在,则什么也不会发生,但是如果没有,程序将终止并显示以下错误:
<在抛出'std :: ios_base :: failure'实例之后调用pre>
terminate
what():basic_ios :: clear
zsh:中止(转储内核) ./a.out
但是我希望代码能够捕获异常并显示错误消息。为什么它没有捕获异常?
您可以通过添加-使它在GCC中工作D_GLIBCXX_USE_CXX11_ABI = 0
到命令行。 此处是GCC的有效示例。
从下面的评论(尤其是LogicStuff的测试)和我自己的测试看来,在clang和MSVC中,它不会产生此错误。
感谢LogicStuff的评论上面我们现在知道这是一个 GCC错误。因为在GCC C ++ 03中ios :: failure并非源自runtime_error,因此没有被捕获。
另一种选择可能是更改为:
尝试
{
MyClass(filename);
}
捕获(std :: ifstream :: failure e)
{
std :: cerr<< 读取文件\n时出错;
}
捕获(...)
{
std :: cerr<< 其他错误\n;
}
Im trying to catch an exception thrown when an error ocurred reading a file in a class method from main. The simplified code is this:
#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;
}
}
I compile this code with:
$ g++ -std=c++11 main.cpp
If file.txt exists nothing happens, but when it doesn't, the program terminates with the following error:
terminate called after throwing an instance of 'std::ios_base::failure'
what(): basic_ios::clear
zsh: abort (core dumped) ./a.out
But I expected the code to catch the exception and show the error message. Why is it not catching the exception?
You can get it to work in GCC by adding -D_GLIBCXX_USE_CXX11_ABI=0
to the command line. Here is a working example with GCC.
From the comments (especially LogicStuff's tests) below and my own test it seems that in clang and MSVC it does not produce this error.
Thanks to LogicStuff's comment above we now know that this is a GCC bug. Because in GCC C++03 ios::failure doesn't derive from runtime_error and so was not caught.
Another option could be to change to:
try
{
A MyClass(filename);
}
catch (std::ifstream::failure e)
{
std::cerr << "Error reading file\n";
}
catch (...)
{
std::cerr << "Some other error\n";
}
这篇关于在main中捕获ifstream异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!