我希望下面的代码调用我的unexpected处理程序,但是我的terminate处理程序被调用了:
#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开发者指南明确鼓励通过set_unexpected()
安装自定义的意外处理程序。我做错了什么,或者这只是c++ -Builder 6中的一个bug ?
当抛出意外异常时,调用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
。
当发生未捕获的异常时,调用 terminate
int main()
{
throw 1; // terminate
}
发生意外异常时,调用 unexpected
。
void foo() throw(int)
{
throw "unexpected will be called.";
}
int main()
{
foo();
}
我将向您展示发生terminate/unexpected的示例程序:
#include <cstdlib>
#include <iostream>
#include <exception>
#define TEST_TERMINATE
void my_terminate()
{
std::cout << "terminate!" << std::endl;
std::abort();
}
void my_unexpected()
{
std::cout << "unexpected!" << std::endl;
std::abort();
}
void foo() throw(int)
{
throw "unexpected will be called.";
}
int main()
{
std::set_terminate(my_terminate);
std::set_unexpected(my_unexpected);
#ifdef TEST_TERMINATE
throw 1;
#else
foo();
#endif
}
(终止的实例,unexpected)