2012-03-12 128 views
31

作爲使用.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 /例外 – 2012-03-12 16:01:18

回答

28

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

+0

我們是否需要使用_ifstream_ _file_作爲類型?我們可以使用_ofstream_嗎? – penguin2718 2015-05-14 18:41:50

+1

假設你正在寫一個文件,那麼你可以用與ofstream相同的方式管理異常。使用ofstream :: failbit,ofstream :: badbit和ofstream :: failure。 – KarlM 2015-05-14 22:40:03

+0

@LightnessRacesinOrbit爲什麼它錯了? – KarlM 2016-09-23 20:44:33

0

我覺得while (!file.eof())聲明不應該在try範圍..

+0

這是一個好主意,雖然你的答案只有真正完成,如果你將你的答案併入他的代碼,然後顯示它的代碼片段? – Frits 2016-09-08 06:27:20

+0

@ muiz您是否建議您在閱讀文件時想要以與打開文件時不同的方式處理錯誤條件?聽起來不錯。 – KarlM 2016-09-23 20:47:15