为什么可以指定异常规范的参数类型?

时间:2017-06-11 14:51:29

标签: c++

为什么你可以在抛出另一个类型时指定throw关键字的参数类型?一个例子:

class A {};
class B {};

void tryexcept() throw(B*)
{
    B* b = new B();
    A* a = new A();
    throw (a); // It works pretty smooth?
}
Int main()
{
try {
        tryexcept();
    }
    catch (A* style)
    {
        cout << "in handler for A\n";

    }
    catch (B* style)
    {
        cout << "in handler for B\n";

    }
    catch (...)
    {
        cout << "in handler for everything\n";

    }
return 0;
}

输出:

in handler for A

顺便说一下。我正在使用Visual Studio。

但是在函数声明中,我将throw的参数类型设置为B*,那么如何抛出A*类型的对象?我的意思是它的工作就像我已经声明了void tryexcept() throw(A*)这样的函数,因为正在使用正确的catch块。

1 个答案:

答案 0 :(得分:1)

根据Microsoft自己的文档see herehere,Visual Studio在处理动态异常规范方面脱离了C ++标准。

它会像写void tryexcept() throw()一样对待此案例。如果使用Visual Studio,则在这种情况下不会调用std :: unexpected。 Microsoft文档警告说,如果从函数中抛出异常,该程序可能无法正常运行,期望是一个人不会。它似乎有&#34;工作&#34;在这种情况下。

如果尝试抛出未指定类型的异常,那么C ++标准行为应该是调用std :: unexpected,而std :: unexpected应该调用terminate()。

此功能在C ++ 11及更高版本中已弃用。