我希望以下代码调用我的意外 处理程序,但调用了我的终止 处理程序:
#include <except>
#include <iostream>
void my_terminate() {
std::cerr << "my terminate handler";
std::exit(0);
}
void my_unexpected() {
std::cerr << "my unexpected handler";
std::exit(EXIT_FAILURE);
}
#pragma argsused
int main(int argc, char* argv[])
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
try {
throw std::exception();
} catch (const std::logic_error&) {
}
return 0;
}
C++ Builder 6 Developer's Guide明确鼓励通过 set_unexpected()
安装自定义意外处理程序。 我做错了什么,或者这只是 C++-Builder 6 中的错误?
最佳答案
通过调用 std::set_unexpected
(对于 std::unexpected
)设置的处理程序将在抛出意外异常时调用;不是在未处理异常时。当违反动态异常规范时调用意外处理程序。
举例说明;
void my_terminate() {
std::cerr << "my terminate handler";
std::exit(0);
}
void my_unexpected() {
std::cerr << "my unexpected handler";
std::exit(EXIT_FAILURE);
}
void function() throw() // no exception in this example, but it could be another spec
{
throw std::exception();
}
int main(int argc, char* argv[])
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
try {
function();
} catch (const std::logic_error&) {
}
return 0;
}
输出是
my unexpected handler
由 std::set_terminate
设置的处理程序由 std::terminate
调用(出于引用中列出的众多原因)。这里有趣的是,当抛出异常但未捕获异常时,默认行为是调用 std::terminate
。
关于c++ - 为什么没有调用 unexpected 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25403585/