Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" , i.e. GCC version 6.2

like image 404
yar Avatar asked Jun 13 '17 03:06

yar


1 Answers

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

like image 105
Jake Askeland Avatar answered Sep 28 '22 05:09

Jake Askeland