从catch块中的函数重试
Rethrow from a function in the catch block
在这种情况下,我想根据抛出的异常执行一些操作,然后重新抛出异常。这是推荐的吗?我的目标是根据抛出的异常做一些工作,并重新引发它,使应用程序崩溃,并生成异常中包含调用堆栈的转储。
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:未捕获异常
相关文章:
- C++变量在调用 x64 程序集函数后重置为 0
- 变量始终在函数中重置为默认值
- C libcurl错误重试
- 为什么当循环再次运行时,此输出"请重试"?
- 网络tcp套接字应用程序重试方法
- 正在重试包含同一异常的exception_ptr的多个实例
- 未收到确认时如何执行数据包重试
- 出现异常后重试本地静态变量初始化
- LIBMEMCACHED :服务器已失败并禁用,直到定时重试
- Android 冻结在 OpenGL|ES 中(CPU 可能被固定,重试)
- 从catch块中的函数重试
- 通过使用构造函数重命名类来C++替代类实现
- 在Poco 1.5.x中使用锁定的SQLite数据库重试
- 'PolishStack'不是类模板,虚函数重影错误
- CURL请求失败重试方法
- "相机正在使用中。关闭使用它的所有应用程序,然后重试。在黑莓 Z10 中调用黑莓 10 级联中的相机时
- 函数重定义错误
- 正在重试异常
- 使用构造函数重定义
- c++中的函数重声明