如何从c++ catch(..)块获取错误消息
How to get the error message from a C++ catch(...) block?
所以,我正在查看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
}
我看到在下面的示例中,您可以像这样捕获"e"数据:
std::cout << e.what();
所以我的问题归结为:
如何获取catch(...)
上的异常数据?
(附带问题:使用catch(...)
是否明智?)
一般情况下不能。c++允许抛出几乎任何东西。例如,throw 42;
是定义良好的c++代码,异常类型是int
。
至于使用它是明智的-有有效的用途:
- 如果抛出一个异常,并且一直没有捕获块,则调用
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;
}
如何获取
catch(...)
上的异常数据?
一般情况下,不能得到任意异常。但是,如果异常类型是已知类型之一,则可以重新抛出当前异常并捕获它。
附带问题:使用
catch(...)
是否明智?)
使用at作为回退选项来处理意外异常是有意义的。可以考虑使用catch-rethrow技术来避免在多个地方复制粘贴catch系列。
void Catcher()
{
try
{
throw;
}
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 (...) {
// oops!
}
}
int main()
{
try {
f();
}
catch (...) {
Catcher();
}
}
相关文章:
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 获取 clang++:错误:在编译文件系统库的代码时
- 从两个 4x64 位整数数组中获取取模
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 尝试使用类时获取标识符错误
- 从'deleted function'获取内存错误
- 获取生成错误:错误 C2011:'ProfileSettings':'class'类型重定义
- 在编写代码以查找数组中的对数时获取分段错误
- C++ 获取线错误。如何避免此错误?"没有重载函数"getline"的实例
- 获取分段错误(代码在 c++ 中转储
- 为代码厨师中的每个代码获取 SIGEMT 错误
- 获取分段错误,用于在 protobuffer 的 C++ 中实现 ByteSize()
- 在C++中获取" expected a ; "错误消息
- 如何在预期类型更改时获取编译器错误
- 当我尝试构建和运行C 程序时,获取Xcode错误代码
- 在 GMock API GetValueAndDelete() 中获取分段错误
- 创建指针 C++ 时获取段错误
- 在Hepsort程序中获取Sigabrt错误
- 在标题文件中获取声明错误
- 使用 getline 函数获取分段错误