简体   繁体   中英

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

I tried the example 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 runs, but prints should not reach this , while I was expecting it to print Exception opening/reading/closing file .

Why is my expectation wrong?

EDIT: since this seems to be an important point, here's the exact version om my compiler: mingw-w64 version "x86_64-6.2.0-posix-sjlj-rt_v5-rev1" , ie GCC version 6.2

This may be a MingW bug. I get the expected result using MacOS Clang 802.0.42. The expected output being:

Exception opening/reading/closing file

This might be a known regression: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66145

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM