3

So, by default std::ifstream doesn't throw an exception when you open an invalid file path. It rather silently fails and if you don't use the fail() method or similar to check, it will easily go unnoticed which is quite bad.

Since I want to get exceptions on any kind of failures so I can be informed automatically, I tried using the exceptions() method as suggested here:

std::ifstream input_stream;
input_stream.exceptions(std::ifstream::badbit);
input_stream.open(file_path);

To my surprise this still doesn't throw an exception if the file path does not exist. I tried using std::ios::badbit instead but same result.

I tested on Ubuntu with GCC.

Why does this not work as expected?

BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
  • 3
    Take another look at [documentation for `open`](https://en.cppreference.com/w/cpp/io/basic_fstream/open). – chris Feb 25 '21 at 18:40
  • Re: "which is quite bad" -- it doesn't silently fail. You can check that it succeeded. And any input operations will also fail. You can't just blindly try a bunch of input without ever checking whether it succeeded. Lots of programmers successfully write complex programs without requiring exceptions on I/O failures. – Pete Becker Feb 25 '21 at 20:23
  • 1
    @PeteBecker: Sure but checking return values is quite an outdated and cumbersome way of programming when we have exceptions. – BullyWiiPlaza Feb 26 '21 at 12:44

1 Answers1

3

On failure, open() sets failbit, not badbit. You are not asking the ifstream to throwing an exception on failbit.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770