javacodex.com
Java Examples
Java Examples
memu home questions

Chained Exceptions

An application often responds to an exception by throwing another exception. In effect, the first exception causes the second exception.

Source: (ChainedException.java)

public class ChainedException {
  public static void main(String[] args) {
 
    try {
      System.out.println("Inside first try");
      throw new Exception();
    } catch (Exception e1) {
      System.out.println("caught: " + e1.toString());
      System.out.println("Inside first catch");
 
      try {
        System.out.println("Inside second try");
        int x = 10 / 0;
      } catch (Exception e2) {
        System.out.println("caught: " + e2.toString());
        System.out.println("Inside second catch");
      }
 
    }
  }
}

Output:

$ java ChainedException 
Inside first try
caught: java.lang.Exception
Inside first catch
Inside second try
caught: java.lang.ArithmeticException: / by zero
Inside second catch

Contact: javacodex@yahoo.com