Posted on Leave a comment

The throw Statement – Exception Handling

7.4 The throw Statement

Earlier examples in this chapter have shown how an exception can be thrown implicitly by the JVM during execution. Now we look at how an application can programmatically throw an exception using the throw statement. This statement can be used in a method, a constructor, or an initializer block. The general format of the throw statement is as follows:

Click here to view code image

throw
object_reference_expression
;

The compiler ensures that the type of the object reference expression is a Throwable or one of its subclasses. This ensures that a Throwable will always be propagated. At runtime a NullPointerException is thrown by the JVM if the object reference expression evaluates to null.

A detail message is often passed to the constructor when the exception object is created.

Click here to view code image

throw new ArithmeticException(“Integer division by 0”);

Propagation of a programmatically thrown exception is no different from one thrown implicitly by the JVM. When an exception is thrown, normal execution is suspended. The JVM proceeds to find a catch clause that can handle the exception.

The search starts in the context of the current try block, propagating to any enclosing try blocks and through the JVM stack to find a handler for the exception. Any associated finally clause of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, normal execution resumes after the code in its catch clause has been executed, barring any rethrowing of an exception.

In Example 7.7, an exception is thrown by the throw statement at (4) as the count value is 0. This exception is propagated to the printAverage() method, where it is caught and handled by the catch clause at (1). Note that the finally clause at (2) is executed, followed by the resumption of normal execution, as evident from the output of the print statement at (3).

Example 7.7 Throwing Exceptions Programmatically

Click here to view code image

public class Average7 {
  public static void main(String[] args) {
    printAverage(100, 0);            // Calling with 0 number of values.
  }
  public static void printAverage(int totalSum, int totalCount) {
    System.out.println(“Entering printAverage().”);
    try {
      int average = computeAverage(totalSum, totalCount);
      System.out.println(“Average = ” +
          totalSum + ” / ” + totalCount + ” = ” + average);
    } catch (ArithmeticException ae) {                             // (1)
      ae.printStackTrace();
      System.out.println(“Exception handled in printAverage().”);
    } finally {                                                    // (2)
      System.out.println(“Finally in printAverage().”);
    }
    System.out.println(“Exit printAverage().”);                    // (3)
  }
  public static int computeAverage(int sum, int count) {
    System.out.println(“Computing average.”);
    if (count == 0)
      throw new ArithmeticException(“Integer division by 0”);      // (4)
    return sum/count;
  }
}

Output from the program:

Click here to view code image

Entering printAverage().
Computing average.
java.lang.ArithmeticException: Integer division by 0
      at Average7.computeAverage(Average7.java:26)
      at Average7.printAverage(Average7.java:11)
      at Average7.main(Average7.java:5)
Exception handled in printAverage().
Finally in printAverage().
Exit printAverage().