Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
 }
}
like image 483
Mr. Boy Avatar asked Oct 11 '12 13:10

Mr. Boy


People also ask

What happens if a class based exception occurs?

If a class-based exception is not handled in a procedure, the system attempts to propagate it to the caller of the procedure. The exceptions that can be propagated from a procedure must be declared in its interface. The caller then knows which exceptions to expect from the procedure.

How do you handle exceptions in C?

Exception Handling Using try-catch block When that statement is executed an exception is generated, which is caught by the catch block. The object of the type IndexOutOfRangeException is used to display a message to the user about the exception that has occurred.

Will a catch statement catch a derived exception if it is looking for the base class?

Catching base and derived classes exceptions in C++To catch an exception for both base and derive class then we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.

How does exception handling work in OOP?

In Object-Oriented Programming (OOP), exceptions are a powerful mechanism for centralized processing of errors and exceptional situations. This mechanism replaces the procedure-oriented method of error handling in which each function returns a code indicating an error or a successful execution.


2 Answers

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

like image 174
Dmitry Ledentsov Avatar answered Oct 04 '22 04:10

Dmitry Ledentsov


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.

like image 41
chmeee Avatar answered Oct 04 '22 03:10

chmeee