2012-04-26 149 views
7

刻意我在這個方法中寫入一個文件,所以我試圖處理,我正在寫到封閉的文件方法可行的例外:ofstream的異常處理

void printMe(ofstream& file) 
{ 
     try 
     { 
      file << "\t"+m_Type+"\t"+m_Id";"+"\n"; 
     } 
     catch (std::exception &e) 
     { 
      cout << "exception !! " << endl ; 
     } 
}; 

但顯然STD: :異常對於一個關閉的文件錯誤來說不是合適的例外,因爲我故意試圖在一個已經關閉的文件上使用這個方法,但是沒有生成我的「異常!!」註釋。

那麼我應該寫些什麼異常?

回答

12

流默認情況下不會拋出異常,但您可以通過函數調用file.exceptions(~goodbit)來告訴它們拋出異常。

相反,檢測錯誤的正常方式是簡單地檢查流的狀態:

if (!file) 
    cout << "error!! " << endl ; 

這樣做的原因是,有許多共同的情況下無效的讀取是一個小問題,而不是一個大之一:

while(std::cin >> input) { 
    std::cout << input << '\n'; 
} //read until there's no more input, or an invalid input is found 
// when the read fails, that's usually not an error, we simply continue 

相比:

for(;;) { 
    try { 
     std::cin >> input; 
     std::cout << input << '\n'; 
    } catch(...) { 
     break; 
    } 
} 

親身體驗:http://ideone.com/uWgfwj

+0

嗯,我只是試圖習慣於異常處理,但很高興知道「Streams默認情況下不會拋出異常」,非常感謝 – Glolita 2012-04-26 17:00:15

4

異常類型ios_base::failure的,但是請注意,你應該設定ios::exceptions相應的標誌來生成指示錯誤,這是默認的行爲將被設爲例外,否則只有內部狀態標誌爲流。