Chained Exception

Chained Exception was added to Java in JDK 1.4. This feature allow you to relate one exception with another exception, i.e one exception describes cause of another exception. For example, consider a situation in which a method throws an ArithmeticException because of an attempt to divide by zero but the actual cause of exception was an I/O error which caused the divisor to be zero. The method will throw only ArithmeticException to the caller. So the caller would not come to know about the actual cause of exception. Chained Exception is used in such type of situations.

Two new constructors and two methods were added to Throwable class to support chained exception.

  1. Throwable( Throwable cause )
  2. Throwable( String str, Throwable cause )

In the first form, the paramter cause specifies the actual cause of exception. In the second form, it allows us to add an exception description in string form with the actual cause of exception.

getCause() and initCause() are the two methods added to Throwable class.

  • getCause() method returns the actual cause associated with current exception.
  • initCause() set an underlying cause(exception) with invoking exception.

Example

import java.io.IOException;
public class ChainedException 
 {
  public static void divide(int a, int b)
  {
   if(b==0)
   {
    ArithmeticException ae = new ArithmeticException("top layer");
    ae.initCause( new IOException("cause") );
    throw ae;
   }
   else
   {
    System.out.println(a/b);
   }
  }

 public static void main(String[] args)
 {
  try {
   divide(5, 0);
  } 
  catch(ArithmeticException ae) {
   System.out.println( "caught : " +ae);
   System.out.println("actual cause: "+ae.getCause());
  }
 }
}

Output :

caught:java.lang.ArithmeticException: top layer
actual cause: java.io.IOException: cause