Chained exception in Java


Chained exception helps to relate one exception to other. Often we need to throw a custom exception and want to keep the details of an original exception that in such scenarios we can use the chained exception mechanism. Consider the following example, where we are throwing a custom exception while keeping the message of the original exception.

Example

Live Demo

public class Tester {
   public static void main(String[] args) {
      try {
         test();
      }catch(ApplicationException e) {          
         System.out.println(e.getMessage());
      }
   }  

   public static void test() throws ApplicationException {
      try {
         int a = 0;
         int b = 1;
         System.out.println(b/a);
      }catch(Exception e) {
         throw new ApplicationException(e);
      }
   }
}

class ApplicationException extends Exception {
   public ApplicationException(Exception e) {          
      super(e);
   }
}

Output

java.lang.ArithmeticException: / by zero

The throwable class supports chained exception using the following methods:

Constructors

  • Throwable(Throwable cause) - the cause is the current exception.

  • Throwable(String msg, Throwable cause) - msg is the exception message, the cause is the current exception.

Methods

  • getCause - returns actual cause.

  • initCause(Throwable cause) - sets the cause for calling an exception.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 18-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements