[4411] in java-interest
Re: finally statement
daemon@ATHENA.MIT.EDU (Ken Arnold - Sun Labs)
Fri Dec 22 12:31:16 1995
Date: Fri, 22 Dec 1995 10:38:25 -0500
From: arnold@suneast.East.Sun.COM (Ken Arnold - Sun Labs)
To: java-interest@webrunner.neato.org
>I've been reading about exception handling in the JDK-beta2 tutorial
>(/java/ exceptions/* group of html files). I read the reasons for
>having a finally block at the end of a try-catch block in
>/java/exceptions/finally.html, but I still don't understand the need
>for a finally block. Since control will be passed to the statement
>following the try-catch block anyway, why should I bother typing in a
>finally block?
The finally block is always executed. The statement after the
try/catch is *not* always executed. Consider the following:
try {
// ... do something ...
} catch (IllegalArgumentException e) {
// ... report the error ...
} finally {
System.out.println("Finally!");
}
System.out.println("Meanwhile...");
Several things can happen that prevent "Meanwhile..." from being
printed. The "try" block can execute a return statement, or if inside
a loop, could continue or break. If it is inside a labelled statement
it could also break. The code inside the try can throw a different
exception[*]. In *all* of these cases the code will print "Finally!".
Ken
[*] If you tried to prevent *this* situation by catching Throwable, you
would be making a Big Mistake. You would, for example, prevent the
thread in which this code was executing from every being stopped()
because you would catch a ThreadDeath exception. Such catch-all catch
clauses are deeply dangerous and should be avoided -- only catch what
you need to catch.
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com