Moshe Moshe - 1 year ago 116
C++ Question

Exception Handling and Opening a File?

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


For example:

ifstream input;

//Catch exception here

If so, what type is

Answer Source

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

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


  return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download