儘管這個問題是相當老已經回答了很多,我只想補充就怎麼做適當的異常處理在C++ 11的說明,因爲我不斷地失蹤這在有關異常的討論:
它是通過寫一個適當的異常處理程序在計算器上here和here,你怎麼能對你例外你的代碼中得到回溯,而不需要一個調試器或繁瑣的記錄,描述了將重新嵌套的excep蒸發散。
由於您可以對任何派生的異常類執行此操作,因此可以將大量信息添加到此類回溯中! 您還可以看看我的MWE on GitHub,其中回溯會是這個樣子:
Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"
你甚至不需要爲了得到足夠的信息,以繼承std::runtime_error
時拋出一個異常。
我在子類中看到的唯一好處(而不是僅使用std::runtime_error
)是您的異常處理程序可以捕獲您的自定義異常並執行一些特殊的操作。例如:
try
{
// something that may throw
}
catch(const MyException & ex)
{
// do something specialized with the
// additional info inside MyException
}
catch(const std::exception & ex)
{
std::cerr << ex.what() << std::endl;
}
catch(...)
{
std::cerr << "unknown exception!" << std::endl;
}
你可能想看看這個:http://stackoverflow.com/questions/1605778/1605852#1605852 – sbi 2009-11-03 23:31:51
雖然作爲一個側面說明無關的特定問題,* C++ *類你不需要永遠成爲可靠的良好實踐資源,只是出於自己的權利。 – 2013-05-28 15:25:00