Types of exception in java with examples easy 20’s


Types of exception in java with examples

Aim to handle exception in java

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

Exception in java small Description before coding

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 |Types of exception in java

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();

                        }

            }

}

Types of exception in java | Result

exception in java

Recommended Posts

Types of exception in java with examples | a source code

Have any Question or Comment?

Leave a Reply

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

Categories