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:
S
Shyam Dubey     View Profile
If you are good in any field. Just share your knowledge with others.