使用C ++打开不存在的文件未捕获到异常 [英] Exception not caught opening a non-existing file using C++
问题描述
我从此处运行MWE:
http:// www .cplusplus.com / reference / ios / ios / exceptions /
在我的计算机上,它没有捕获到异常。这是我的代码
I was running a MWE from here: http://www.cplusplus.com/reference/ios/ios/exceptions/ On my machine it does not catch the exception. Here is my code
#include <iostream>
#include <fstream>
int main()
{
std::ifstream file;
file.exceptions( std::ifstream::failbit | std::ifstream::badbit );
try
{
file.open("IDoNotExist.txt");
}
catch(const std::ifstream::failure& e)
{
std::cout << "Bad luck!" << std::endl;
}
}
使用 gcc 6.2.1 $ c在Arch-Linux上$ c>我得到:
在抛出'std :: ios_base :: failure'实例后调用终止
terminate called after throwing an instance of 'std::ios_base::failure'
what():basic_ios :: clear
what(): basic_ios::clear
但是,在上面发布的链接中提到代码也应该捕获异常与打开文件有关。出了什么问题?
However, on the link posted above it is mentioned that the code should also catch the exception related to opening the file. What went wrong?
推荐答案
它看起来像是 libstdc ++中的已知错误。
问题在于更改为C ++ 11 ABI,许多类在 libstdc ++ 6.so
中重复,一个版本使用旧的ABI,另一个版本使用新的ABI。
The problem is that with the change to the C++11 ABI, many classes were duplicated in libstdc++6.so
, one version with the old ABI, other with the new one.
异常类没有重复,因此该问题当时不存在。但是,随后,在对该语言的一些较新版本中,决定 std :: ios_base :: failure
应该源自 std :: system_error
而不是 std :: exception
...,但是 system_error
是C ++ 11唯一的类因此它必须使用新的ABI标志,否则它将抱怨。现在,您有了两个不同的 std :: ios_base :: failure
类,并且手头一团糟!
Exception classes were not duplicated so this problem didn't exist at the time. But then, in some newer revision of the language, it was decided that std::ios_base::failure
should derive from std::system_error
instead of std::exception
... but system_error
is a C++11 only class so it must use the new ABI flag or it will complain. Now you have two different std::ios_base::failure
classes and a mess in your hands!
简单解决方案是使用 -D_GLIBCXX_USE_CXX11_ABI = 0
编译您的程序,然后辞职到旧的ABI,直到错误解决为止。或者,编写 catch(std :: exception& e)
。
The easy solution is to compile your program with -D_GLIBCXX_USE_CXX11_ABI=0
and resign to the old ABI until the bug is solved. Or alternatively, write catch (std::exception &e)
.
这篇关于使用C ++打开不存在的文件未捕获到异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!