Reputation: 19225
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?
Upvotes: 5
Views: 2574
Reputation: 597360
On failure, open()
sets failbit
, not badbit
. You are not asking the ifstream
to throwing an exception on failbit
.
Upvotes: 5