Types of exception in java with examples

Types of exception in java with examples

7 b) Aim: To Use inheritance to create an exception super class called Exception A and exception sub class Exception B and Exception C, where Exception B inherits from Exception A and Exception C inherits from Exception B. Write a java program to demonstrate that the catch block for type Exception A catches exception of type Exception B and Exception C

Description :

Create a class ExceptionA which extends Exception class. Create ExceptionB and ExceptionC classes, such that ExceptionB inherits from ExceptionA and ExceptionC inherits from ExceptionB.   The catch block for type ExceptionA

catches exception of type ExceptionB and ExceptionC

source code :

import java.io.*;

import java.util.*;

class ExceptionA extends Exception

{

             ExceptionA(String message)

            {

                        super(message);

            }

}

 class ExceptionB extends ExceptionA

{

             ExceptionB(String message)

            {

                        super(message);

            }

            public static void getExceptionB() throws Exception

            {

                        throw new ExceptionB(“Exception B”);

            }

}

 class ExceptionC extends ExceptionB

{

             ExceptionC(String message)

            {

                        super(message);

            }

            public static void getExceptionC() throws Exception

            {

                        throw new ExceptionC(“ExceptionC”);

            }

}

class TestException

{

            public static void main(String ar[]) throws Exception

            {

                        try

                        {

                                    ExceptionB.getExceptionB();

                        }

                        catch(ExceptionA ea)

                        {

                                    System.out.println(“In B”);

                                    ea.printStackTrace();

                        }

                        try

                        {

                                    ExceptionC.getExceptionC();

                        }

                        catch(ExceptionA ea)

                        {

                                    System.out.println(“In C”);

                                    ea.printStackTrace();

                        }

            }

}

Output :

Types of exception in java with examples

Leave a Comment

Your email address will not be published. Required fields are marked *