Saturday, May 27, 2006

Can we Skip finally block?

Is it possible to skip the 'finally' block even though its present after a try/catch block. i.e

try{
...//write some code here to make finally never execute.
}finally{
...
}

Give me some possible ways to achieve this?

Ans:

1. System.exit(1);
2. Thread - wait() strategy.

try {
final Object o = new Object();
synchronized(o) {
o.wait();
}
}
finally {
System.out.println("blah");
}

My point being that this -- and any number of other "solutions" -- isn't actually skipping the finally at all; just delaying -- perhaps for an infinite time -- reaching it. There really is no way to skip it (unless you want to count System.exit() -- even that is cheating, really, as you're only skipping it by terminating the program. Truly "skipping it" would mean continuing the same thread in the same program after the try block completes, and that's not possible.


Using System.exit() doesn't skip anything, it merely terminates the entire JVM before the code is executed. If you consider the termination of a JVM before the execution of a finally block "skipping" the finally block then by that definition all code is skipped. It is impossible to skip a finally block.

0 Comments:

Post a Comment

<< Home