异常处理和打开文件?

Mos*_*she 38 c++ exception-handling inputstream file-handling

是否可以使用文件打开的异常作为使用的替代方法.is_open()

例如:

ifstream input;

try{
  input.open("somefile.txt");
}catch(someException){
  //Catch exception here
}
Run Code Online (Sandbox Code Playgroud)

如果是这样,那是什么类型的someException

Kar*_*rlM 40

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

另请阅读本答案11085151,它引用了本文

// 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;
}
Run Code Online (Sandbox Code Playgroud)

Wandbox上运行的示例代码

编辑:通过const引用2145147捕获异常

编辑:从异常集中删除failbit.添加了URL以获得更好的答案