开发者

Can a function throw derived class exception when its exception specification has base type?

i have the following code.

class Base{};
class Derived: public Base{};

class Test
{
public:
    void fun() throw(Base)
    {
        throw Derived();
    }
};

int main()
{
    Test ob; ob.fun();
}

Can function fun() throw exceptions of derived types when its exception specification l开发者_StackOverflow中文版ist has base type ?


Since Derived derives from Base, it technically is-a Base. So, yes, you can throw derived exception types if your method signature lists their base type.

But note that, as @MSalters says, there are issues with exception specifications.


Short answer is, yes it can, longer one : Don't use functions exception specifications. In new standard C++0x it will be deprecated.

Why they deprecate it? Because in C++ exception specification not working like in java. If you try to throw something else , you will not get any compilation error( like in java). In runtime it will call std::unexpected() function, which will call unexpected handler function, which by default will terminate the program.


Yes, that's fine. A function allows an exception of type E if its exception specification contains a type T such that a handler for a type T would match for an exception of type E (C++ standard 2003, 15.4)


This is absolutely correct. Sure it can, you can catch the exception by ref (to the base class) and re-throw it, for example.

//..
try
{
    ob.fun();
}
catch( Base& ex )
{
    // do something with the exception;

    // throw;  // if you want it to be re-thrown
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜