7

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

Galik
  • 47,303
  • 4
  • 80
  • 117
yar
  • 1,855
  • 13
  • 26
  • Could you try using `while (file.good()) {` ? – xsami Jun 13 '17 at 03:16
  • 1
    @xsami same story. The exception is thrown in `file.open("not_existing.txt");` – yar Jun 13 '17 at 03:19
  • I would recommend `char c; while(file.get(c)) {}` Never loop using `eof()` https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Jun 13 '17 at 03:27
  • @Galik thanks, but that's just the example code from http://www.cplusplus.com. I have the same behavior in totally different code. – yar Jun 13 '17 at 03:31
  • 3
    You should catch both exceptions by reference. At present you have one by value, one by reference. – user207421 Jun 13 '17 at 07:35
  • @EJP you're right. The first one is just directly taken from the example, I decided not to change it to keep the changes minimal. – yar Jun 13 '17 at 15:27

1 Answers1

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

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Jake Askeland
  • 253
  • 2
  • 6