如何从C++ catch(...)块获取错误消息?

Cod*_*ker 2 c++ try-catch

所以,我正在查看try/catch块的C++参考.

我看到有几种方法可以捕获异常,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

我在以下示例中看到您可以捕获"e"数据,如下所示:

std::cout << e.what();
Run Code Online (Sandbox Code Playgroud)

所以我的问题归结为:

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

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

krz*_*zaq 7

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

至于使用它是明智的 - 有效用途:

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

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

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

try {
//...
} catch(...) {
    log() << "Unknown exception!";
    throw;
}
Run Code Online (Sandbox Code Playgroud)