53

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
  • 398,270
  • 210
  • 566
  • 880
Moshe
  • 57,511
  • 78
  • 272
  • 425

2 Answers2

53

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,614
  • 18
  • 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
  • If you remove `ios_base::failbit` you don't get an exception when the file does not exist. Just replace `test.txt` with `test2.txt` and see for yourself. It won't throw anything. If you ask me, just don't use `ios_base::exceptions()`. It's completely botched up... – Elmar Zander Feb 07 '23 at 12:01
3

From the cplusplus.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.

Don Yanda
  • 65
  • 7
DumbCoder
  • 5,696
  • 3
  • 29
  • 40