next up previous
Next: Example of exception handling Up: Unit 10 Previous: Propagation of exceptions

Interrupting the propagation of exceptions

In the following example, the exception is not handled in the method that generates it, but in a method that invokes the method that generates the exception. Then, the exception is not further propagated upwards. Hence, the first() and main() methods do not have to declare in the throws clause that they throw the exception.

import java.io.*;

public class ExceptionPropagation2 {

  public static void main(String[] args) throws IOException {
    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) {
    try {
      second(a);
    }
    catch (Exception e) {
      System.out.println("Exception handled in the first method.");
      System.out.println(e.getMessage());
    }
  }

  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");
  }
}

The result of the execution of this program for the same input as before, is the following:

Insert a number:
5
Exception handled in the first method.
The value is too small.


next up previous
Next: Example of exception handling Up: Unit 10 Previous: Propagation of exceptions