bjskishore123
bjskishore123

Reputation: 6342

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 list has base type ?

Upvotes: 4

Views: 1094

Answers (4)

UmmaGumma
UmmaGumma

Reputation: 5693

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.

Upvotes: 3

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262919

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.

Upvotes: 3

Tim Martin
Tim Martin

Reputation: 3697

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)

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38153

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
}

Upvotes: 0

Related Questions