MS不按套路出牌——Visual Studio 2005中的set_unexpected

读到《More Effective C++》 中这一条Item 14:  Use exception specifications judiciously.的时候,打开VS操作了一下,因为以前没有用过set_unexpected,所以想看看到底如何神奇。写了下面一段程序:

void ThrowExp()
{
 throw string("Error");
}

void DoSomething() throw(int)
{
 ThrowExp();
}

void Convert()
{
 cout << "Convert() is called" << endl;
}

int main(int argc, char* argv[])
{
 try
 {
  DoSomething();
 }
 catch(...)
 {
  cout << "Hello1" << endl;
 } 

 set_unexpected(Convert);
 DoSomething();

 cout << "Hello2" << endl;

 return 1;
}

运行程序,在控制台输出:


Hello1

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Press any key to continue . . .

也就是说在第一次调用DoSomething()的时候,程序并没有终止,但是按照标准C++的说法,似乎此时由于函数DoSomething()抛出了与异常规范不符的异常,程序会调用unexpected(),而unexpected()会默认调用terminate(),接着terminate()会默认调用abort(),最后程序终止。
在第二次调用DoSomething()的时候,由于此时已经调用set_unexpected()设置了unexpected()的调用函数,按照标准C++的说法,此时由于函数DoSomething()抛出了与异常规范不符的异常,程序会调用unexpected(),而unexpected()会调用set_unexpected()所设置的Convert(),从而输出Convert() is called,但结果是未有任何输出,程序非正常终止。

不得已,查阅MSDN里set_unexpected()用法,发现一下这句话:
In the current Microsoft implementation of C++ exception handling, unexpected calls terminate by default and is never called by the exception-handling run-time library. There is no particular advantage to calling unexpected rather than terminate.

似乎MS不愿意按套路出牌,他并没有调用unexpected,而是直接调用了terminate。即便是这样解释也不对,因为如果直接调用了terminate的话,继而会调用abort,如此一来程序便会终止,而不会输出Hello1了。

这么看来,难道在visual studio2005里面,异常规范只会起到在编译时刻警告作者的用处?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值