49

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?

Bill the Lizard
  • 386,424
  • 207
  • 554
  • 861
Moshe
  • 56,717
  • 76
  • 267
  • 423

2 Answers2

50

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

Also read this answer 11085151 which references this article

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

void do_something_with(char ch) {} // Process the character 

int main () {
  ifstream file;
  file.exceptions ( ifstream::badbit ); // No need to check failbit
  try {
    file.open ("test.txt");
    char ch;
    while (file.get(ch)) do_something_with(ch);
    // for line-oriented input use file.getline(s)
  }
  catch (const ifstream::failure& e) {
    cout << "Exception opening/reading file";
  }

  file.close();

  return 0;
}

Sample code running on Wandbox

EDIT: catch exceptions by const reference 2145147

EDIT: removed failbit from the exception set. Added URLs to better answers.

KarlM
  • 1,574
  • 17
  • 28
  • Do we need to use _ifstream_ _file_ as type? Could we use _ofstream_? – penguin2718 May 14 '15 at 18:41
  • 1
    Assuming you are writing to a file, then yes you can manage exceptions the same way with ofstream. Use ofstream::failbit, ofstream::badbit and ofstream::failure. – KarlM May 14 '15 at 22:40
  • @KarlM: Ehm in this case it isn't wrong. Although it _is_ redundant. – Lightness Races in Orbit Sep 24 '16 at 13:56
  • BTW catch exceptions by reference – Lightness Races in Orbit Sep 24 '16 at 13:57
  • 1
    I shall point out your code is not working as you may think. The exception will be thrown when you encounter the EOF because you set `ifstream::failbit` as exception mask, at least on Mac OS 10.10 Yesomite. If a file is read when EOF is encountered, `ios_base::failbit` will be set together with `ios_base::eofbit`. – Han XIAO Jun 29 '18 at 03:38
2

From the cppreference.com article on std::ios::exceptions

On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.

Lightness Races in Orbit
  • 369,052
  • 73
  • 620
  • 1,021
DumbCoder
  • 5,706
  • 3
  • 28
  • 40