Coupon Accepted Successfully!


Exceptions And Inheritance

In the last few examples, we have learned how the exception mechanism works with the operator function and with constructors and destructors. The following program explains how exception handling can be done with inheritance:

19.11 Write a program to throw an exception in derived class.


class ABC



char name[15];

int age;


class abc : public ABC // public derivation


float height;

float weight;


void getdata()


cout<<“\n Enter Name and Age:”;


if (age<=0)

throw abc();

cout<<“\n Enter Height and Weight:”;

cin>>height >>weight;


void show()


cout<<“\n Name:”<<name<<“\n Age:”<<age<<“ Years”;

cout<<“\n Height:”<<height<<“Feets”<<“\n Weight:” <<weight<<“Kg.”;



void main()




abc x;

x.getdata(); // Reads data through keyboard.

x.show(); // Displays data on the screen.


catch (abc) { cout<<“\n Wrong age”; }



Enter Name and Age: Amit 0

Wrong age

Explanation: In the above program, the two classes ABC and abc are declared. The class ABC has two protected data members name and age. The class abc has two float data members’ height and weight with two member functions getdata() and show(). The class abcis derived from class ABC. The statement class abc: public ABC defines the derived class abc. In the function main(), x is an object of the derived class abc. The object x invokes the member function getdata() and show(). This function reads and displays data, respectively. In the function getdata(), the if statement checks the age entered. If the age entered is zero or less than zero, an exception is thrown. The catch block is executed, and the message Wrong age” is displayed.

Test Your Skills Now!
Take a Quiz now
Reviewer Name