读到《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里面,异常规范只会起到在编译时刻警告作者的用处?