在C++中,在异常声明说明符中,如果我声明一个基类,然后抛出一个派生类,是不是意外异常?
最佳答案
In C++, in the exception declaration specifier, if I declare a base class and then throw a derived class, is that an unexpected exception?
没有。这是允许的。
引用: C++03 15.4 异常规范
第 6 段:
An exception-specification can include the same type more than once and can include classes that are related by inheritance, even though doing so is redundant. An exception-specification can also include the class std::bad_exception (18.6.2.1).
中有一个相关的例子
第 8 段:
[Example:
class X { };
class Y { };
class Z: public X { };
class W { };
void f() throw (X, Y)
{
int n = 0;
if (n) throw X(); // OK
if (n) throw Z(); // also OK <------- Example of the exact scenario you posted
throw W(); // will call unexpected()
}
—end example]
请注意,异常规范被视为失败的实验,大多数编译器都没有正确实现它们。所以避免(而不是不)使用它们。
关于c++ - 来自异常声明的派生对象类型是否意外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10227317/