Chained Exceptions

The chained exception allows you to associate another exception with an exception. This second exception describes the cause of the first exception.

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


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

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


public class Main {
  static void demoproc() {
    NullPointerException e = new NullPointerException("top layer");
    e.initCause(new ArithmeticException("cause"));
    throw e;
  }

  public static void main(String args[]) {
    try {
      demoproc();
    } catch (NullPointerException e) {
      System.out.println("Caught: " + e);
      System.out.println("Original cause: " + e.getCause());
    }
  }
}
Home 
  Java Book 
    Language Basics  

Exception Handler:
  1. Exception Handling
  2. Exception Types
  3. try and catch
  4. Displaying a Description of an Exception
  5. Multiple catch Clauses
  6. Nested try Statements
  7. Creates and throws an exception
  8. Methods with throws clause
  9. finally
  10. Java's Built-in Exceptions
  11. Creating Your Own Exception Subclasses
  12. Chained Exceptions