A try statement without a finally block is executed by first executing the try block. Then there is a choice:
-
If execution of the
tryblock completes normally, then no further action is taken and thetrystatement completes normally. -
If execution of the
tryblock completes abruptly because of athrowof a valueV, then there is a choice:-
If the run-time type of
Vis assignment compatible with (§5.2) a catchable exception class of anycatchclause of thetrystatement, then the first (leftmost) suchcatchclause is selected. The valueVis assigned to the parameter of the selectedcatchclause, and the Block of thatcatchclause is executed, and then there is a choice:- If that block completes normally, then the
trystatement completes normally. - If that block completes abruptly for any reason, then the
trystatement completes abruptly for the same reason.
- If that block completes normally, then the
-
If the run-time type of
Vis not assignment compatible with a catchable exception class of anycatchclause of thetrystatement, then thetrystatement completes abruptly because of athrowof the valueV.
-
-
If execution of the
tryblock completes abruptly for any other reason, then thetrystatement 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