N.B. std::ifstream::failure
is a type defined in the std::ios_base
base class of ifstream
, so the rest of this answer refers to it as std::ios_base::failure
or just std::ios::failure
.
The problem here is that since GCC 5 there are two different definitions of std::ios_base::failure
in libstdc++ (see the Dual ABI docs for more details). That's needed because C++11 changed the definition of ios::failure
from:
class ios_base::failure : public exception {
to:
class ios_base::failure : public system_error {
This is an ABI change, because system_error
has additional data members compared to exception
, and so it changes the size and layout of ios::failure
.
So since GCC 5.1, when your code names std::ios_base::failure
(or std::ifstream::failure
or any other name for it) which definition you get depends on the value of the _GLIBCXX_USE_CXX11_ABI
macro. And when an iostream error happens inside the libstdc++.so
library, which type gets thrown depends on the value of the macro when libstdc++.so
was built. If you try to catch one type and the library throws the other type, the catch won't work. This is what you're seeing. In your code std::ifstream::failure
names the new type, but the library is throwing the old type, which is a different class, so the catch handler isn't matched.
With GCC 5.x and 6.x the code inside libstdc++.so
throws the old type, so to catch it you need to either compile you code with -D_GLIBCXX_USE_CXX11_ABI=0
or change your handler to catch (const std::exception&)
(because both the old and new types derive from std::exception
).
With GCC 7.x the code inside the library throws the new type (changed by PR 66145), so you need to compile your code with -D_GLIBCXX_USE_CXX11_ABI=1
or catch std::exception
.
For GCC 8.x the library now throws an exception type that can be caught by a handler for the old type or the new type (changed by PR 85222), so you don't need to change your code. It will Just Work™.
failure
exception and print "Bad luck!" (assumingIDoNotExist.txt
genuinely does not exist). Therefore, your C++ compiler and/or runtime are malfunctioning. The most probable reason for this is that they are mis-installed. Try uninstalling and reinstalling every package withg++
orc++
in its name. – zwol