Mr. Boy
Mr. Boy

Reputation: 63720

How does C++ exception handling deal with exception derived classes?

If I am catching BaseException will this also catch exceptions which derive from BaseException? Does exception handling care about inheritance, etc, or does it only match the exact exception type being caught?

class MyException {
...
};
class MySpecialException : public MyException {
...
};

void test()
{
 try {
 ...
 }
 catch (MyException &e) {
   //will this catch MySpecialException?
 }
}

Upvotes: 8

Views: 6122

Answers (5)

user2314671
user2314671

Reputation: 11

include

class ExceptionBase { };

class MyException : public ExceptionBase { };

int main() { try { throw MyException(); } catch (MyException const& e) { std::cout<<"catch 1"<

////////
try
{
    throw MyException();
}
catch (ExceptionBase const& e) {
    std::cout<<"catch 2"<<std::endl;
}
catch (...) {
    std::cout<<"should not catch 2"<<std::endl;
}

return 0;

Upvotes: 1

Benj
Benj

Reputation: 32398

Yes it will, this is very common. It's common for example to catch std::exception despite the fact that the exception thrown is likely to be a derived exception like std::bad_alloc or std::runtime_error.

You can actually catch the base type and the derived and they will be caught in turn, but you must catch the derived type first.

try
{
   // code which throws bad_alloc
}
catch ( const std::bad_alloc & e )
{
   // handle bad_alloc
}
catch ( const std::exception & e )
{
   // catch all types of std::exception, we won't go here 
   // for a bad_alloc because that's been handled.
}
catch ( ... )
{
   // catch unexpected exceptions
   throw;
}

Upvotes: 3

Dmitry Ledentsov
Dmitry Ledentsov

Reputation: 3660

It's easy to explain with code: http://ideone.com/5HLtZ

#include <iostream>

class ExceptionBase {
};

class MyException : public ExceptionBase {
};

int main()
{
    try
    {
        throw MyException();
    }
    catch (MyException const& e) {
        std::cout<<"catch 1"<<std::endl;
    }
    catch (ExceptionBase const& e) {
        std::cout<<"should not catch 1"<<std::endl;
    }

    ////////
    try
    {
        throw MyException();
    }
    catch (ExceptionBase const& e) {
        std::cout<<"catch 2"<<std::endl;
    }
    catch (...) {
        std::cout<<"should not catch 2"<<std::endl;
    }

    return 0;
}

output:
catch 1
catch 2

Upvotes: 8

chmeee
chmeee

Reputation: 3638

C++ exception handling will match the exception subclasses. However, it performs a linear search from the first catch() to the last, and will only match the first one. So if you intend to catch both Base and Derived, you would need to catch(MySpecialException &) first.

Upvotes: 6

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143061

Yes, it will catch exceptions derived from the base.

Upvotes: 1

Related Questions