● 函数的声明
unexpected_handler set_unexpected (unexpected_handler f) throw();
设置新的,返回旧的
● 说明
所谓的unexpected_handler,指的是函数。
如果某个函数出现异常,而该异常未被列到异常列表,则unexpected_handler被系统自动调用。
该函数可以调用 terminate 或者 cstdlib::exit 或者 cstdlib::abort 中止程序的执行。
也可以把异常再次抛出,或者抛出别的异常。
如果抛出的异常不在异常列表,而且列表里有 bad_exception,那么系统会代替它抛出 bad_exception。
如果列表里没有 bad_exception,那么系统自动调用 terminate 终止程序的运行。
默认的 unexpected handler 调用 terminate。
● demo
#include <iostream> #include <exception> using namespace std; void myunexpected () { 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) { set_unexpected (myunexpected); try { myfunction(); } catch (int) { cerr << "caught int\n"; } catch (...) { cerr << "caught other exception (non-compliant compiler?)\n"; } return 0; }
在VC2008上运行这个程序时,没有如期的运行myunexpected函数。
正确输出应为:
unexpected called
caught int
据说GCC是正常的。
本文详细介绍了C++中unexpected_handler的作用及使用方法。当遇到未在异常列表中声明的异常时,unexpected_handler会被调用。文中通过一个示例展示了如何自定义unexpected_handler,并探讨了不同编译器下的行为差异。
5万+

被折叠的 条评论
为什么被折叠?



