std::set_unexpected
当函数抛出的异常不在dynamic-exception-specification包含的时候。异常可以被set_unexpected的函数捕获,然后可以调用terminate函数或者其它的方法,比如 exit或者abort。当然也可以重新抛出异常,但如果新抛出的异常不在dynamic-exception-specification里面的话,terminate会默认执行。
example:
// set_unexpected example
#include <iostream> // std::cerr
#include <exception> // std::set_unexpected
void myunexpected () {
std::cerr << "unexpected called\n";
throw 0; // throws int (in exception-specification)
}
void myfunction () throw (int) {
throw 'x'; // throws char (not in exception-specification)
}
int main (void) {
std::set_unexpected (myunexpected);
try {
myfunction();
}
catch (int) { std::cerr << "caught int\n"; }
catch (...) { std::cerr << "caught some other exception type\n"; }
return 0;
}
output:
unexpected called
caught int
std::set_terminate
当throw的异常没有捕获的时候,会调用set_terminate设置的函数。
eg:
// set_terminate example
#include <iostream> // std::cerr
#include <exception> // std::set_terminate
#include <cstdlib> // std::abort
void myterminate () {
std::cerr << "terminate handler called\n";
abort(); // forces abnormal termination
}
int main (void) {
std::set_terminate (myterminate);
throw 0; // unhandled exception: calls terminate handler
return 0;
}
output:
terminate handler called
Aborted