9

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

ildjarn
  • 60,915
  • 9
  • 122
  • 205
Adam Lee
  • 23,314
  • 47
  • 144
  • 221

1 Answers1

14

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.

Adam Lee
  • 23,314
  • 47
  • 144
  • 221
πάντα ῥεῖ
  • 85,314
  • 13
  • 111
  • 183