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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Virtual functions in derived classes
- Nested Classes in C++
- Hiding of all overloaded methods with same name in base class
- Local Classes in C++
- What happens when more restrictive access is given to a derived class method in C++?
- Pure Virtual Functions and Abstract Classes in C++
- C++ Classes and Objects
- Trivial classes in C++
- Publicly inherit a base class but making some of public method as private
- Anonymous classes in C++
- File Handling through C++ Classes
- Difference between fundamental data types and derived data types
- Virtual base class in C++
- C++ Stream Classes Structure
- Derived Data Types in C++
- Enum Classes in C++ and Their Advantage over Enum DataType
- Storage Classes in C++ with Examples
- Difference between Base class and Derived class in C++
- Mutual friendship of Classes in C++ with Examples
- How to add reference of an object in Container Classes