I am trying to use
std::ifstream inStream;
inStream.open(file_name);
If file_name
does not exists, no exception is thrown. How can I make sure to throw in this case? I am using C++11
You can do so by setting the streams exception mask, before calling open()
std::ifstream inStream;
inStream.exceptions(std::ifstream::failbit);
try {
inStream.open(file_name);
}
catch (const std::exception& e) {
std::ostringstream msg;
msg << "Opening file '" << file_name
<< "' failed, it either doesn't exist or is not accessible.";
throw std::runtime_error(msg.str());
}
By default none of the streams failure conditions leads to exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With