我有这个代码:
#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/