C++ 异常处理和打开文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9670396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exception Handling and Opening a File?
提问by Moshe
Is it possible to use exceptions with file opening as an alternative to using .is_open()
?
是否可以使用打开文件的异常作为使用的替代方法.is_open()
?
For example:
例如:
ifstream input;
try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}
If so, what type is someException
?
如果是,是什么类型someException
?
回答by KarlM
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
Also read this answer 11085151which 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
在Wandbox 上运行的示例代码
EDIT: catch exceptions by const reference 2145147
编辑:通过常量引用2145147捕获异常
EDIT: removed failbit from the exception set. Added URLs to better answers.
编辑:从异常集中删除了故障位。添加了 URL 以获得更好的答案。
回答by DumbCoder
From the cppreference.com article on std::ios::exceptions
来自cppreference.com 上的文章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.
失败时,failbit 标志被设置(可以使用成员 fail 来检查),并且根据设置的异常值可能会抛出异常。