Re: what's the point in finally?
Crouchez wrote:
"Patricia Shanahan" <pats@acm.org> wrote in message
news:13bgsvc2rdrkkfc@corp.supernews.com...
Crouchez wrote:
Scenario A
try{
//blah
}
catch(Exception e){
}
finally{
//do something
}
why not just...
Scenario B
try{
//blah
}catch(Exception e){
}
//do something
OK right. I'm not following the arguments here. The //do something will
always be called in both scenarios unless something isn't returned in the
catch method? I don't understand why there is more use of resources
either in Scenario B? So what's the use of finally?
In the second scenario //do something will not be called if, for
example, there was a stack overflow, because StackOverflowError does not
extend Exception.
are you sure? whether code throws an exception/error/throwable or not it
will still get to //do something in both scenarios. With StackOverflowError
or OutofMemoryError then the program often stops completely.
I am sure. This program:
public class StackOverflowTest {
public static void main(String[] args) {
try {
try {
badRecursion();
} catch (Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("In finally block");
}
System.out.println("After try-catch-finally");
} catch (StackOverflowError e) {
System.out.println("Caught " + e);
}
}
static void badRecursion() {
badRecursion();
}
}
prints:
In finally block
Caught java.lang.StackOverflowError
It does not reach the "After try-catch-finally" printout.
In many cases a program could in theory continue after an Error, but it
is usually not a good idea. Error implies that something is VERY wrong.
Also consider the case in which //blah contains a return statement. Code
immediately after the try-catch-finally will not get executed. The
finally block will.
Ahh i see this point. I thought return was the ultimate last in the chain -
finally does indeed get called before return but i can't think of any reason
to do that.
finally allows you to write return statements where they logically
belong and yet be sure the method's clean-up code runs.
When I saw try-catch-finally, I knew I would not miss "goto". The few
goto's I wrote in C were all emulating a finally structure, making sure
that no matter how I completed a function I would do the cleanup.
Patricia