

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Algorithm
Begin Declare a class B. Declare another class D which inherits class B. Declare an object of class D. Try: throw derived. Catch (D derived) Print “Caught Derived Exception”. Catch (B b) Print “Caught Base Exception”. End.
Here is a simple example where catch of derived class has been placed before the catch of base class, now check the Output
#include<iostream> using namespace std; class B {}; class D: public B {}; //class D inherit the class B int main() { D derived; try { throw derived; } catch(D derived){ cout<<"Caught Derived Exception"; //catch block of derived class } catch(B b) { cout<<"Caught Base Exception"; //catch block of base class } return 0; }
Output
Caught Derived Exception
Here is a simple example where catch of base class has been placed before the catch of derived class, now check the Output
#include<iostream> using namespace std; class B {}; class D: public B {}; //class D inherit the class B int main() { D derived; try { throw derived; } catch(B b) { cout<<"Caught Base Exception"; //catch block of base class } catch(D derived){ cout<<"Caught Derived Exception"; //catch block of derived class } return 0; }
Output
Caught Base Exception Thus it is proved that we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.
- Related Questions & Answers
- What are Base and Derived Classes in C#?
- Virtual functions in derived classes in C++
- Python Exception Base Classes
- Interpreter base classes in Python
- Abstract Base Classes in Python (abc)
- What is the base class for errors and exceptions in Java?
- Python Abstract Base Classes for Containers
- What is the base class for all exceptions in C#?
- Pseudo-classes and CSS Classes
- Catching the ball game using Python
- Pseudo-classes and all CSS Classes
- Exceptions and Error in PHP 7
- Difference between Copy and Derived view in SAP HANA
- User defined and custom exceptions in Java
- Difference between fundamental data types and derived data types
Advertisements