How to catch an I / O exception (exactly I / O, not std :: exception)

I tried the sample program from here (with mingw-w64). The program crashed. So I edited it:

#include <iostream>     // std::cerr
#include <fstream>      // std::ifstream

int main()
{
    std::ifstream file;
    file.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    try {
        file.open("not_existing.txt");
        while (!file.eof())
            file.get();
        file.close();
    }
    catch (std::ifstream::failure e) {
        std::cerr << "Exception opening/reading/closing file\n";
    }
    catch (const std::exception& e) {
        std::cerr << "should not reach this";
    }

    return 0;
}

Now it starts, but prints should not reach thiswhile I was waiting for printing Exception opening/reading/closing file.

Why is my expectation wrong?

EDIT: since this seems to be an important point, here is the exact om version of my compiler: mingw-w64 version "x86_64-6.2.0-posix-sjlj-rt_v5-rev1", i.e. GCC version 6.2

+6
source share
1 answer

This may be a MingW error. I get the expected result using MacOS Clang 802.0.42. Expected Result:

//

: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145

+2

All Articles