Java Reference
In-Depth Information
Example 14.20.2-1. Handling An Uncaught Exception With
finally
class BlewIt extends Exception {
BlewIt() { }
BlewIt(String s) { super(s); }
}
class Test {
static void blowUp() throws BlewIt {
throw new NullPointerException();
}
public static void main(String[] args) {
try {
blowUp();
} catch (BlewIt b) {
System.out.println("Caught BlewIt");
} finally {
System.out.println("Uncaught Exception");
}
}
}
This program produces the output:
Uncaught Exception
Exception in thread "main" java.lang.NullPointerException
at Test.blowUp(Test.java:7)
at Test.main(Test.java:11)
The
NullPointerException
(which is a kind of
RuntimeException
) that is thrown by method
blowUp
is not caught by the
try
statement in
main
, because a
NullPointerException
is not
assignable to a variable of type
BlewIt
. This causes the
finally
clause to execute, after
which the thread executing
main
, which is the only thread of the test program, termin-
ates because of an uncaught exception, which typically results in printing the excep-
tion name and a simple backtrace. However, a backtrace is not required by this spe-
cification.
The problem with mandating a backtrace is that an exception can be created at one
point in the program and thrown at a later one. It is prohibitively expensive to store a
stack trace in an exception unless it is actually thrown (in which case the trace may be
generated while unwinding the stack). Hence we do not mandate a back trace in every
exception.