如何避免在 catch 块中编写重复代码
How to avoid writing repeated code in catch blocks?
我正在使用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 块中编写清理代码吗?有什么方法可以避免编写重复的代码吗?
注意:: [ 在方法1() 中 ] 我想重新抛出发生的异常 给我的来电者。所以我不能在单个捕获块中捕获它们, 因为这样类型信息就会丢失。
Method1 可以通过两个概念来简化:
- 雷伊。将任何清理代码放入析构函数中,清理代码将被集中化。
- 使用非限定
throw
,您无需知道引发的异常类型。
因此,method1()
应如下所示:
void method1()
{
// some initializations of RAII objects
// some operations (here exceptions can occur)
}
如果从 std::exception
派生 Exception1,则可以删除 callerMethod
中的第一个 catch
子句,因为 what()
方法是虚拟的。
您应该抛出尽可能低的异常,并在调用链中尽可能高地捕获它们。这会自动减少代码重复,并集中错误处理。你在一个地方扔/接住所有东西,这似乎有点......强迫。
我经常做这种事情(特别是对于程序结束异常:
int main()
try
{
function_calls_that_may_throw();
// ...
}
catch(my_exception& e)
{
e.do_exception_stuff();
}
catch(std::exception& e)
{
std::cout << e.what();
}
catch(...)
{
std::cout << "Something bad happened.n";
}
这仅适用于抛出您不打算更好地处理或重试失败操作或其他内容的异常。
这种方法的优点是所有/大多数错误处理代码都位于程序的顶层,调用链中的所有函数都不必担心这些东西,它们所做的只是在他们愿意的时候抛出异常。
如果你所有的清理代码都是完全相同的,你可以在你的catch(...)块中做所有事情:
try {
// code
} catch (...) {
// cleanup
throw;
}
如果代码略有不同,则始终可以调用清理函数:
try {
// code
} catch (exc1 ex) {
cleanup(args);
// exc1 specific
throw;
} catch (exc2 ex) {
cleanup(args);
// exc2 specific
throw;
} catch (...) {
cleanup(args);
throw;
}
相关文章:
- 以下示例中如何避免代码复制?C++/库达
- 是否应该在模板化代码中完全避免const
- 避免在遍历 IShellItemArray 时出现代码重复
- 将函数作为参数传递以避免重复代码
- 标准对此指向成员函数类型模板参数有何说明?是我的代码有误,还是 MSVS 16.6 有问题?
- 继承、覆盖和虚函数,以避免重复代码
- 避免易失性和非易失性成员函数的代码重复
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 避免使用 std::any 编写相同的重复类型检查代码
- 在多个头文件中从接口声明被覆盖的函数时,如何避免重复代码?
- 是否可以避免在以下代码中复制/移动构造函数的需要?
- 简化代码以避免在顺时针旋转2D矩阵时出现TLE
- 如何避免大多数成员功能相同的代码重复
- 如何在这样的代码中避免 TLE?
- 如何组织耗时的代码以避免开销
- 如何重写此代码以避免使用全局
- 如何在C++代码中避免这些类型的内存泄漏
- 如何重构这段简单的代码以避免代码重复
- 任何人都可以修改以下代码以避免使用"if"吗?
- 是否可以更改此代码以避免使用C++lambda表达式