Java Reference
In-Depth Information
• 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
14.20.2. Execution of
try
-
finally
and
try
-
catch
-
finally
A
try
statement with 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 the
finally
block is executed,
and then there is a choice:
♦ If the
finally
block completes normally, then the
try
statement completes nor-
mally.
♦ If the
finally
block completes abruptly for reason
S
, then the
try
statement com-
pletes abruptly for reason
S
.
• If execution of the
try
block completes abruptly because of a
throw
of a value
V
,
then there is a choice: