5.8 'throw' Statement

Earlier examples in this chapter have shown how an exception is thrown implicitly during execution. A program can explicitly throw an exception using the throw statement. The general format of the throw statement is as follows:


throw <object reference expression>;

The compiler ensures that the <object reference expression> is of type Throwable class or one of its subclasses. At runtime a NullPointerException is thrown if the <object reference expression> is null. This ensure that a Throwable will always be propagated. A detail message is often passed to the constructor when the exception object is created.

throw new ArithmeticException("Integer division by 0");

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a catch block 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 runtime stack to find a handler for the exception. Any associated finally block 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, execution resumes with the code in its catch block.

In Example 5.15, an exception is thrown using a throw statement at (17). This exception is propagated to the main() method where it is caught and handled by the catch block at (3). Note that the finally blocks at (6) and (14) are executed. Execution continues normally from (7).

Example 5.15 Throwing Exceptions
public class Average7 {

    public static void main(String[] args) {
        try {                                                      // (1)
            printAverage(100, 0);                                  // (2)
        } catch (ArithmeticException ae) {                         // (3)
            ae.printStackTrace();                                  // (4)
            System.out.println("Exception handled in " +           // (5)
                               "main().");
        } finally {
            System.out.println("Finally in main().");              // (6)
        }
        System.out.println("Exit main().");                        // (7)
    }

    public static void printAverage(int totalSum, int totalNumber) {
        try {                                                      // (8)
            int average = computeAverage(totalSum, totalNumber);   // (9)
            System.out.println("Average = " +                      // (10)
                totalSum + " / " + totalNumber + " = " + average);
        } catch (IllegalArgumentException iae) {                   // (11)
            iae.printStackTrace();                                 // (12)
            System.out.println("Exception handled in " +           // (13)
                               "printAverage().");
        } finally {
            System.out.println("Finally in printAverage().");      // (14)
        }
        System.out.println("Exit printAverage().");                // (15)
    }

    public static int computeAverage(int sum, int number) {
        System.out.println("Computing average.");
        if (number == 0)                                           // (16)
            throw new ArithmeticException("Integer division by 0");// (17)
        return sum/number;                                         // (18)
    }
}

Output from the program:

Computing average.
Finally in printAverage().
java.lang.ArithmeticException: Integer division by 0
        at Average7.computeAverage(Average7.java:35)
        at Average7.printAverage(Average7.java:19)
        at Average7.main(Average7.java:6)
Exception handled in main().
Finally in main().
Exit main().