是否可以使用异常处理来替代使用 .is_open()
进行文件打开操作?
例如:
ifstream input;
try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}
如果是这样,someException
是哪种类型?
是否可以使用异常处理来替代使用 .is_open()
进行文件打开操作?
例如:
ifstream input;
try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}
如果是这样,someException
是哪种类型?
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
// 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::failbit
设置为异常掩码,至少在Mac OS 10.10 Yesomite上是这样。如果在遇到EOF时读取文件,则会设置ios_base::failbit
和ios_base::eofbit
。 - Han XIAOios_base::failbit
,当文件不存在时就不会抛出异常。只需将 test.txt
替换为 test2.txt
并自行查看。它不会抛出任何异常。如果问我,就别使用 ios_base::exceptions()
。它完全搞砸了... - Elmar Zander来自cplusplus.com有关std::ios::exceptions
的文章
如果发生故障,将设置failbit标志(可以使用成员fail进行检查),并根据使用exceptions设置的值可能会抛出异常。