我使用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