c++ - 覆盖默认的未处理异常行为

标签 c++ c++11 exception-handling g++ visual-studio-2015

我有这个代码:

#include <iostream>
#include <exception>

class TestException : public std::exception
{
public:
    char const* what() const throw() override { return msg_.c_str(); }

protected:
    std::string & message() throw() { return msg_; }

private:
    std::string msg_;
};

void ThrowIt()
{
    throw TestException();
}

int main()
{
    ThrowIt();
}

在使用 Visual Studio 编译的 Windows 上构建 Release 或 Debug 时运行此命令会导致程序终止,在 Linux 机器上使用 GCC 编译时也是如此,结果是:

terminate called after throwing an instance of 'TestException'
what(): Aborted

一旦捕获到未处理的异常,两者都会终止程序。这种行为是严格的系统特定的还是由标准指定的?有没有一种跨平台的方法可以将 catch 未处理的每个异常重新路由到处理程序,而不是仅仅终止程序?

最佳答案

在您的代码中,您有一个未捕获的异常,因为您的异常没有匹配的句柄。 [except.terminate]

中涵盖了此行为

In some situations exception handling must be abandoned for less subtle error handling techniques. [ Note: These situations are:
[...]
- when the exception handling mechanism cannot find a handler for a thrown exception (15.3), or [...]

然后我们有

In such cases, std::terminate() is called (18.8.3). In the situation where no matching handler is found, it is implementation-defined whether or not the stack is unwound before std::terminate() is called.

如果你想要“顶级”catch 来处理你程序中的所有异常,如果没有被捕获,你可以将代码包装在 main() 中一个 try...catch block 。任何未捕获的异常都将根据 [except.handle] 向上移动

If no match is found among the handlers for a try block, the search for a matching handler continues in a dynamically surrounding try block of the same thread.

您还可以使用 std::set_terminate 更改 std::terminate_handler

关于c++ - 覆盖默认的未处理异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32890507/

相关文章:

c++ - Detours 3.0 钩子(Hook) GetProcAddresss()

c++ - 我不知道结构体和指针的用法

c++ - 带有 std::vector 和带有缩减的标量变量的 OpenMP for 循环

c++ - 在 bitset 中随机选择 set bit 位置的最佳 C++ 方法

c++ - 如何在一个 catch block 中捕获所有类型的异常?

java - ANTLR NoViableAltException 与 JAVA

ruby-on-rails - Rails - rescue_from 异常根据引发异常的方法以不同方式处理异常类型

c++ - 如何将C++程序的已编译逻辑与其余文件头数据区分开?

c++ - 运行 .exe 文件时出现 std::logic 错误

c++ - 函数的嵌套模板参数