std::set_unexpected
當(dāng)函數(shù)拋出的異常不在dynamic-exception-specification包含的時(shí)候氛悬。異程杲剑可以被set_unexpected的函數(shù)捕獲,然后可以調(diào)用terminate函數(shù)或者其它的方法蒂萎,比如 exit或者abort秆吵。當(dāng)然也可以重新拋出異常,但如果新拋出的異常不在dynamic-exception-specification里面的話五慈,terminate會(huì)默認(rèn)執(zhí)行纳寂。
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
當(dāng)throw的異常沒有捕獲的時(shí)候,會(huì)調(diào)用set_terminate設(shè)置的函數(shù)泻拦。
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