You are here: Home / Topics / Chained exception example in Java

Chained exception example in Java

Filed under: Java on 2023-09-19 06:50:25

//  Program to explain Chained Exception.

class  ChainedException
{
static void demoproc() 
{
 NullPointerException e = new NullPointerException("top layer");
 e.initCause(new ArithmeticException("cause"));
 throw e;
}

public static void main(String args[ ]) 
{
 try 
 {
  demoproc();
 } 
 catch(NullPointerException e) 
 {
  System.out.println("Caught: " + e);
  System.out.println("Original cause: " + e.getCause());
 }
}
}


Output:

Caught: java.lang.NullPointerException: top layer
Original cause:  java.lang.ArithmeticException: cause

About Author:
M
Mr. Dubey     View Profile
Founder and CEO of MCQ Buddy. I just like to help others. This portal helps students in getting study material free.