C++中的异常处理:使用"throw(int)"时抛出一个double

use*_*696 8 c++ double int try-catch

以下程序始终输出"错误:双10.2".

我不懂为什么.根据我的说法,如果fun1()只允许抛出int,程序应该(1)崩溃(2)或将double更改为int然后抛出.这意味着,输出应为"Error:int 10".然而,事实并非如此.谁能解释一下?

void fun1() throw (int)
{
    cout<<"3";
    throw 10.2;
    cout<<"4";
}

int main()
{
    try {   fun1(); }
    catch(int i) { cout<<"Error:int" <<i <<endl;}
    catch(double i) { cout << "Error:double" << i << endl; }
    cout << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Tad*_*pec 9

您的编译器不符合标准.根据标准,你的程序应该std::unexpected在让double异常逃脱后以调用结束fun1.
也就是说 - 不要使用异常规范.它们已被弃用且无用.

  • 以下是关于原因主题的有趣读物:http://www.gotw.ca/publications/mill22.htm (3认同)