我使用QT 4.8(C++),用於桌面應用程序的項目,並編寫異常處理是如下:如何避免在catch塊中寫入重複的代碼?
void callerMethod()
{
try
{
method1();
}
catch(Exception1& e)
{
// display critcal error message
// abort application
}
catch(std::Exception& e)
{
// print exception error message
}
catch(...)
{
// print unknown exception message
}
}
void method1()
{
try
{
// some initializations
// some operations (here exceptions can occur)
// clean-up code (for successful operation i.e no exception occurred)
}
catch(Exception1& e)
{
// clean-up code
throw e;
}
catch(Exception2& e)
{
// clean-up code
throw e;
}
catch(Exception3& e)
{
// clean-up code
throw e;
}
catch(...)
{
// clean-up code
throw;
}
}
所以我的問題,我需要寫清理代碼在每一個catch塊 ? 有什麼辦法可以避免重複編寫代碼?
注意 :: [在方法1()]我想重新拋出異常發生 我caller.So我不能趕上他們在一個catch塊, 由於然後鍵入的信息將會丟失。
Try t o減少使用智能指針,容器類等所需的清理代碼的數量。理想情況下,應該沒有任何清理代碼。 – user763305 2012-04-21 06:43:59
看來你想要做的只是'try {/ * may throw * /} catch(specific_exception const&e){/ * terminate * /}'。如果你不關心異常類型'Exception1','Exception2'等等,那麼*不會*捕獲它們。 – 2012-04-21 07:54:51
此外,即使你通過引用來捕獲,你應該*使用'throw;'rethrow而不是'throw e;'來防止切片。 – ereOn 2012-04-21 08:25:42