Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

ifstream - Exception not caught opening a non-existing file using C++

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;
    }
}

Using gcc 6.2.1 on Arch-Linux I get:

terminate called after throwing an instance of 'std::ios_base::failure'

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like a known bug in libstdc++.

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.

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!

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...