c++ - 如何从 C++ catch(...) block 中获取错误消息?

标签 c++ try-catch

所以,我正在查看 C++ reference对于 try/catch block 。

我看到有几种方法可以像这样捕获异常:

try {
    f();
} catch (const std::overflow_error& e) {
    // this executes if f() throws std::overflow_error (same type rule)
} catch (const std::runtime_error& e) {
    // this executes if f() throws std::underflow_error (base class rule)
} catch (const std::exception& e) {
    // this executes if f() throws std::logic_error (base class rule)
} catch (...) {
    // this executes if f() throws std::string or int or any other unrelated type
}

我在以下示例中看到您可以像这样捕获“e”数据:

std::cout << e.what();

所以我的问题归结为:

如何在 catch(...) 上获取异常数据?

(附带问题:使用 catch(...) 是否明智?)

最佳答案

一般来说,你不能。 C++ 允许抛出几乎任何东西。例如 throw 42; 是定义良好的 C++ 代码,异常的类型是 int

至于明智地使用它 - 有一些有效的用途:

  • 如果抛出异常并且一直没有 catch block ,则调用 std::terminate 并且无法保证堆栈展开。 catch(...) 保证(因为它捕获任何异常)。

int main()
{
    super_important_resource r;
    may_throw();
    // r's destructor is *not* guaranteed to execute if an exception is thrown
}

int main()
try {
    super_important_resource r;
    may_throw();
    // r's destructor is guaranteed to execute during stack unwinding
} catch(...) {
}
  • 在重新抛出异常之前记录抛出的异常是一个有效的用例。

try {
//...
} catch(...) {
    log() << "Unknown exception!";
    throw;
}

关于c++ - 如何从 C++ catch(...) block 中获取错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40343193/

相关文章:

c++ - 如何从 qml 启动一个 Qthread?

c++ - 除非存在特定的 printf 语句,否则 fwrite 不会将缓冲区写入标准输出

c++ - 不允许函数模板部分特化 'swap<T>'

java - 使用 try-catch 验证输入

c++ - 在对角正方形中裁剪图像

c++ - 调用删除时 STL 迭代器失效的问题

c# - 唯一列约束,异常与数据库检查?

javascript - 在我的代码末尾使用 .catch 更好吗?

c# - 有没有比在整个应用程序代码中散布 try/catch 更优雅的错误处理方法?

java - 强制 try block 在两者之间中断的最佳方法是什么?