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 modifed 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.
- Writing C/C++ code efficiently in Competitive programming
- Namespace in C++ | Set 1 (Introduction)
- The C++ Standard Template Library (STL)
- Virtual Functions and Runtime Polymorphism in C++ | Set 1 (Introduction)
- Exception Handling in C++
- Can virtual functions be private in C++?
- Multiple Inheritance in C++
- Copy elision in C++
- Catch block and type conversion in C++
- Exception handling and object destruction | Set 1
- Comparison of Exception Handling in C++ and Java
- Templates and Static variables in C++
- Stack Unwinding in C++
- Precedence of postfix ++ and prefix ++ in C/C++
- RTTI (Run-time type Information) in C++