gpt4 book ai didi

c++ - 如何避免在 catch block 中编写重复代码?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:22:13 25 4
gpt4 key购买 nike

我正在为桌面应用程序项目使用 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 block 中编写清理代码吗?有什么方法可以避免编写重复的代码

注意::[ In method1() ] 我想重新抛出发生的异常 给我的来电者。所以我无法在单个 catch block 中捕获它们, 因为那样的话类型信息就会丢失。

最佳答案

方法 1 可以通过两个概念大大简化:

  1. RAII .将任何清理代码放入析构函数中,清理代码将被集中。
  2. 使用非限定的throw,您将不需要知道抛出的异常类型。

因此,method1() 应该如下所示:

void method1()
{
// some initializations of RAII objects
// some operations (here exceptions can occur)
}

如果从 std::exception 派生 Exception1,则可以删除 callerMethod 中的第一个 catch 子句,因为 what( ) 方法是虚拟的。

关于c++ - 如何避免在 catch block 中编写重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10256875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com