所以,我正在查看 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/