作为使用.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;
int main() {
ifstream file;
file.exceptions (ifstream::failbit | ifstream::badbit);
try {
file.open ("test.txt");
while (!file.eof()) file.get();
}
catch (const ifstream::failure& e) {
cout << "Exception opening/reading file";
}
file.close();
return 0;
}
编辑:捕获异常由const引用2145147
我们是否需要使用_ifstream_ _file_作为类型?我们可以使用_ofstream_吗? – penguin2718 2015-05-14 18:41:50
假设你正在写一个文件,那么你可以用与ofstream相同的方式管理异常。使用ofstream :: failbit,ofstream :: badbit和ofstream :: failure。 – KarlM 2015-05-14 22:40:03
@LightnessRacesinOrbit为什么它错了? – KarlM 2016-09-23 20:44:33
从the cppreference.com article on std::ios::exceptions
失败时,failbit标志被设置(其可以与构件失败进行检查),并根据与异常的异常可能抛出设置的值。
HTTP://en.cppreference。 com/w/cpp/io/basic_ios /例外 – 2012-03-12 16:01:18