Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
410 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...