Chained Exception in Java

Category: Java   Tags: Java, Java Basic, Java Exception Handling, Java Chained Exception

Chained exception let us know when one exception causes another. In a real world application one exception causes to throw another exception. Following are the methods and constructors in Throwable to support chained exceptions:

  • Throwable(String message, Throwable cause)
  • Throwable(Throwable cause)

cause is the exception that causes the current exception. That is, cause is the underlying reason that an exception occurred. message is the exception description.

  • Throwable getCause()
  • Throwable initCause(Throwable cause)

getCause() returns the exception that caused the current exception, and initCause sets the current exception's cause.

Here is how to use a chained exception:

JavaChainedExceptionExample.java

                            package com.tutorial.javabasic;

                            public class JavaChainedExceptionExample {

                                static void dummy(String arg) {
                                    if(arg == null) {
                                        IllegalArgumentException ex = new IllegalArgumentException("Input is not a valid string");
                                        ex.initCause(new NullPointerException("Input was a null string."));
                                        throw ex;
                                    }
                                }
                                public static void main(String s[]) {
                                    try {
                                        dummy(null);
                                    } catch(IllegalArgumentException ex) {
                                        System.out.println("Caught exception: " + ex);
                                        System.out.println("Real Cause: " + ex.getCause());
                                    }
                                }
                            }
                        

Output:

                            Caught exception: java.lang.IllegalArgumentException: Input is not a valid string
                            Real Cause: java.lang.NullPointerException: Input was a null string.
                        

Here IllegalArgumentException is the top level exception and NullPointerException is the actual exception that you can get using getCause() method.