异常处理和打开文件?

53

是否可以使用异常处理来替代使用 .is_open() 进行文件打开操作?

例如:

ifstream input;

try{
  input.open("somefile.txt");
}catch(someException){
  //Catch exception here
}

如果是这样,someException 是哪种类型?


1
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions - R. Martinho Fernandes
2个回答

54

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;
}

Wandbox 上运行的示例代码。

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

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


我们需要使用 ifstream 类型的 file 吗?我们可以使用 ofstream 吗? - penguin2718
1
假设您正在写入文件,那么是的,您可以使用ofstream以相同的方式处理异常。使用ofstream::failbit、ofstream::badbit和ofstream::failure。 - KarlM
@KarlM:在这种情况下,它并不是错误的。虽然它是多余的。 - Lightness Races in Orbit
顺便提一下,通过引用捕获异常。 - Lightness Races in Orbit
1
我要指出你的代码并不像你想象的那样工作。当你遇到EOF时,异常将被抛出,因为你将ifstream::failbit设置为异常掩码,至少在Mac OS 10.10 Yesomite上是这样。如果在遇到EOF时读取文件,则会设置ios_base::failbitios_base::eofbit - Han XIAO
如果你移除 ios_base::failbit,当文件不存在时就不会抛出异常。只需将 test.txt 替换为 test2.txt 并自行查看。它不会抛出任何异常。如果问我,就别使用 ios_base::exceptions()。它完全搞砸了... - Elmar Zander

3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接