gpt4 book ai didi

c++ - 从 catch block 中的函数重新抛出

转载 作者:太空宇宙 更新时间:2023-11-04 13:44:16 24 4
gpt4 key购买 nike

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

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 会导致异常。我需要捕获某些状态吗?我该怎么做?

最佳答案

当您捕捉到异常时,您有两种选择:

  • 以某种方式实现最初的目标(契约(Contract)),例如通过重试。
  • 通过 throw 报告失败。

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

关于c++ - 从 catch block 中的函数重新抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26579116/

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