next up previous
Next: Interrupting the propagation of Up: Unit 09 Previous: Example of exception handling

Propagation of exceptions

If an exception is not caught and handled where it is thrown, the control is passed to the method that has invoked the method where the exception was thrown. The propagation continues until the exception is caught, or the control passes to the main method, which terminates the program and produces an error message.

It is the throw statements that starts the chain of method terminations. For example:

import java.io.*;

public class ExceptionPropagation1 {

  public static void main(String[] args) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Insert a number:");
    int c = Integer.parseInt(br.readLine());
    first(c);
  }

  private static void first(int a) throws Exception {
    second(a);
  }

  private static void second(int b) throws Exception {
    Exception propagate = new Exception("The value is too small.");
    if (b < 10)
      throw propagate;
    System.out.println("OK");
  }
}

If the program reads a value less than 10, for example 5, an exception is thrown and the following messages are printed:

Insert a number:
5
Exception in thread "main" java.lang.Exception: The value is too small.
  at ExceptionPropagation1.second(ExceptionPropagation1.java:17)
  at ExceptionPropagation1.first(ExceptionPropagation1.java:13)
  at ExceptionPropagation1.main(ExceptionPropagation1.java:9)

Note that, in order to allow the chain of terminations started by the second method to propagate to the main method, it is necessary that all methods that are part of the termination chain have in their header the throws clause with the list of involved exceptions: in this case, only Exception.


next up previous
Next: Interrupting the propagation of Up: Unit 09 Previous: Example of exception handling