Exception chaining in Java

Java 8Object Oriented ProgrammingProgramming

When one exception is chained to the another, it describes the cause of that exception. Constructors of the Throwable class support chained exceptions in Java. They are as follows −

Throwable(Throwable cause)
Throwable(String msg, Throwable cause)

The Throwable class has methods which support exception chaining −

MethodDescription
getCause()Returns the original cause of the exception
initCause(Throwable cause)Sets the cause for invoking the exception

Let us see an example of exception chaining in Java.

Example

 Live Demo

public class Example {
   public static void main(String[] args) {
      try {
         // creating an exception
         ArithmeticException e = new ArithmeticException("Apparent cause");
         // set the cause of an exception
         e.initCause(new NullPointerException("Actual cause"));
         // throwing the exception
         throw e;
      } catch(ArithmeticException e) {
         // Getting the actual cause of the exception
         System.out.println(e.getCause());
      }
   }
}

Output

java.lang.NullPointerException: Actual cause
raja
Published on 04-Jan-2019 06:23:34
Advertisements