Java Exception chained exceptions

Introduction

The chained exception allows us to associate another exception with an exception.

This second exception specifies the cause of the first exception.

To support chained exceptions, two constructors and two methods were added to Throwable.

Throwable(Throwable causeExc)  
Throwable(String msg, Throwable causeExc) 

causeExc is the exception that causes the current exception.

The chained exception methods supported by Throwable are getCause() and initCause().

Throwable getCause()  
Throwable initCause(Throwable causeExc) 

Here is an example that illustrates the mechanics of handling chained exceptions:

// Demonstrate exception chaining.  
public class Main {
  static void myMethod() {
    // create an exception
    NullPointerException e = new NullPointerException("top layer");
    // add a cause
    e.initCause(new ArithmeticException("cause"));
    throw e;/*from   w  w  w .  ja  v a 2s .c o m*/
  }

  public static void main(String args[]) {
    try {
      myMethod();
    } catch (NullPointerException e) {
      // display top level exception
      System.out.println("Caught: " + e);
      // display cause exception
      System.out.println("Original cause: " + e.getCause());
    }
  }
}

// Chained exceptions.

public class Main
{
   public static void main(String[] args)
   {/*w  ww .j  av a2s  .  co  m*/
      try 
      { 
         method1(); 
      } 
      catch (Exception exception) // exceptions thrown from method1
      { 
         exception.printStackTrace();
      } 
   } 

   // call method2; throw exceptions back to main
   public static void method1() throws Exception
   {
      try 
      { 
         method2(); 
      }
      catch (Exception exception) // exception thrown from method2
      {
         throw new Exception("Exception thrown in method1", exception);
      }
   } // end method method1

   // call method3; throw exceptions back to method1
   public static void method2() throws Exception
   {
      try 
      { 
         method3(); 
      } 
      catch (Exception exception) // exception thrown from method3
      {
         throw new Exception("Exception thrown in method2", exception);
      } 
   } // end method method2

   // throw Exception back to method2
   public static void method3() throws Exception
   {
      throw new Exception("Exception thrown in method3");
   } 
}



PreviousNext

Related