Moshe Moshe - 2 months ago 16
C++ Question

Exception Handling and Opening a File?

Is it possible to use exceptions with file opening as an alternative to using

.is_open()
?

For example:

ifstream input;

try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}


If so, what type is
someException
?

Answer

http://en.cppreference.com/w/cpp/io/basic_ios/exceptions

// ios::exceptions
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ifstream file;
  file.exceptions ( ifstream::failbit | ifstream::badbit );
  try {
    file.open ("test.txt");
    while (!file.eof()) file.get();
  }
  catch (ifstream::failure e) {
    cout << "Exception opening/reading file";
  }

  file.close();

  return 0;
}
Comments