JVM Knowledge

A try statement without a finally block is executed by first executing the try block. Then there is a choice:

  • If execution of the try block completes normally, then no further action is taken and the try statement completes normally.

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

    • If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

      • If that block completes normally, then the try statement completes normally.
      • If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
    • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

  • If execution of the try block completes abruptly for any other reason, then the try statement completes abruptly for the same reason.

Example 14.20.1-1. Catching An Exception

class BlewIt extends Exception {
    BlewIt() { }
    BlewIt(String s) { super(s); }
}
class Test {
    static void blowUp() throws BlewIt { throw new BlewIt(); }

    public static void main(String[] args) {
        try {
            blowUp();
        } catch (RuntimeException r) {
            System.out.println("Caught RuntimeException");
        } catch (BlewIt b) {
            System.out.println("Caught BlewIt");
        }
    }
}

Here, the exception BlewIt is thrown by the method blowUp. The try-catch statement in the body of main has two catch clauses. The run-time type of the exception is BlewIt which is not assignable to a variable of type RuntimeException, but is assignable to a variable of type BlewIt, so the output of the example is:

Caught BlewIt