Types of Exception in Java With Examples

Exception in Java With Examples

Aim of this program:

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

Output:

exception in java

FAQ:

What are the types of exception in Java?

These are the types of Exceptions in Java:
ArithmeticException
ArrayIndexOutOfBounsException
ClassNotFoundException
IOException
InterruptedException
NoSuchFieldException
NoSuchMethodException
NullPointerException
NumberFormatException
RuntimeException
StringIndexOutOfBoundsException

What is an exception in Java with example?

The exception is nothing but types of error that occur at the run time of the program. Example dividing any number with zero ( 23 / 0) #This arises exception.

What is the difference between error and exception?

In java, an error is nothing but a syntactic mistake in the program and it will occur at compile time. But an exception is an error that occurs at the run time of the program, for example: dividing number with zero.There are two types of exceptions i.e. Checked Exception and Unchecked Exception.

Recommended Post:

Find the solution to the salesforce Question and many more

Hi, I’m Pramod Kumar Yadav & a computer science Engineer with 3years of experience in Digital marketing. I’m self-motivated and love to do SEO.

Leave a Reply

%d bloggers like this: