作爲使用.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