Catching base and derived classes as exceptions
Exception Handling – catching base and derived classes as exceptions:
If both base and derived classes are caught as exceptions then catch block of derived class must appear before the base class.
If we put base class first then the derived class catch block will never be reached. For example, following C++ code prints “Caught Base Exception”
In the above C++ code, if we change the order of catch statements then both catch statements become reachable. Following is the modified program and it prints “Caught Derived Exception”
In Java, catching a base class exception before derived is not allowed by the compiler itself. In C++, compiler might give warning about it, but compiles the code.
For example, following Java code fails in compilation with error message “exception Derived has already been caught”
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.