Exception Handling and Opening a File?

社会主义新天地 提交于 2019-12-03 19:11:35

问题


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?


回答1:


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.




回答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.



来源:https://stackoverflow.com/questions/9670396/exception-handling-and-opening-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!