set_unexpected

本文详细介绍了C++中unexpected_handler的作用及使用方法。当遇到未在异常列表中声明的异常时,unexpected_handler会被调用。文中通过一个示例展示了如何自定义unexpected_handler,并探讨了不同编译器下的行为差异。

● 函数的声明
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是正常的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值