从catch块中的函数重试

Rethrow from a function in the catch block

本文关键字:函数 重试 catch      更新时间:2023-10-16

在这种情况下,我想根据抛出的异常执行一些操作,然后重新抛出异常。这是推荐的吗?我的目标是根据抛出的异常做一些工作,并重新引发它,使应用程序崩溃,并生成异常中包含调用堆栈的转储。

class Foo
{
public:
void HandleException(const std::exception& ex)
{
    // Log, report some metrics
    throw;
}
void Work(//Some inputs)
{
     try
     {
          // trying doing some work
     }
     catch (const std::exception& ex)
     {
          // This is really an exceptional situation, and the exception should be thrown which  
          // cause the exe to abort and create dump.
          // Intention is to preserve call stack and have it in dump.
          HandleException(ex);
     }
}
}

让我为这个问题添加另一个注释:当我将HandleException作为lambda函数时,抛出lambda会导致异常。我需要捕捉一些状态吗?我该怎么做?

当您捕获异常时,您有两个选项:

  • 以某种方式实现最初的目标(合同),例如通过重试
  • 通过投掷报告失败

重新处理原始异常是实现第二个要点的一种方法。

是的,这是有效的但是它也很危险。

如果您在没有参数的情况下调用throw;,并且当前飞行中没有异常,则会导致调用std::terminate()。当前代码的问题是,任何人都可以调用该函数,即使他们不在catch块中(这将导致终止)。

因此,您可能需要验证是否存在异常:

void HandleException(const std::exception& ex)
{
    // Log, report some metrics
    if (std::uncaught_exception()) {
        throw;
    }
    // Maybe put an else here.
}

同样值得一读:GotW#47:未捕获异常