【发布时间】:2012-05-02 16:01:10
【问题描述】:
我在桌面应用项目中使用 QT 4.8 (C++),编写异常处理如下:
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 块中编写清理代码吗? 有什么办法可以避免重复编写代码?
注意:: [ In method1() ] 我想重新抛出发生的异常 给我的来电者。所以我无法在单个捕获块中捕获它们, 因为那样类型信息将会丢失。
【问题讨论】:
-
尝试通过使用智能指针、容器类等来减少清理代码的数量。理想情况下根本不应该有清理代码。
-
看来你想做的只是
try { /* may throw */ } catch(specific_exception const& e) { /* terminate */ }。如果您不关心异常类型Exception1、Exception2等等,那么不要捕获它们。 -
此外,即使您确实通过引用捕获,您应该使用
throw;而不是throw e;重新抛出以防止切片。
标签: c++ optimization exception-handling try-catch throw