Java chained exceptions

In this chapter you will learn:

  1. How to use chained exceptions
  2. Syntax for chained exceptions
  3. Example - use chained exceptions

Description

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

Syntax

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


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

Example

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;// ww  w .  ja va 2  s.  c  om
  }

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

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is annotation and how to create an annotation
  2. Syntax to create Java Annotations
  3. Note for Java Annotations
Home »
  Java Tutorial »
    Java Langauge »
      Java Exception Handling
Java Exception
Java Exception types
Java try catch statement
Java throw statement
Java throws statement
Java finally statement
Java Built-in Exceptions
Java custom exception class
Java chained exceptions