We can use Exception handling with class too. Even we can throw an exception of user defined class types. For throwing an exception of say demo class type within try block we may write
Example 1: Program to implement exception handling with single class
Caught exception of demo class
Explanation: In the program we have declared an empty class.In the try block we are throwing an object of demo class type. The try block catches the object and displays.
Example 2: Program to implement exception handling with two class
Caught exception of demo1 class Caught exception of demo2 class
Exception handling with inheritance:
Exception handling can also be implemented with the help of inheritance. In case of inheritance object thrown by derived class is caught by the first catch block.
Caught exception of demo1 class Caught exception of demo1 class
Explanation: The program is similar to previous one but here we have made demo2 as derived class for demo1.Note the catch block for demo1 is written first.As demo1 is base class for demo2 an object thrown of demo2 class will be handled by first catch block.That is why output as shown.
Exception handling with constructor:
Exception handling can also be implemented by using constructor. Though we cannot return any value from the constructor but with the help of try and catch block we can.
Exception caught Zero not allowed Again creating object Num = 1
Explanation: when x = 0 exception is thrown and catch block is called. And when x = 1 no exception is created .