Hi, Well, now I'm confused: I thought a finally block will always be executed, no matter what code is in the catch block. Am I wrong?? well, I had to find out that System.exit(0) in the catch block exits the application without executing the finally block. (which kinda makes sense). But what about a return statement in the finally block, will that be executed or not? Thanks alot.
several circmstances that can prevent the execution of finally block 1. An Exception arising in the finally block without try/catch for handling that exception. 2. the death of the thread. 3. use of System.exit(). 4. power to CPU off.
Quoting The Java Preogramming Language, Third Edition, page 206: A finally clause is always entered with a reason. The reason may be that the try code finished normally, that it executed a ... return, or that an exception was thrown ... The reason is remembered when the finally clause exits by falling out the bottom. However, if the finally block creates its own reason to leave by executing a ... return, ... that reason supercedes the original one and the original reason is forgotten. In short, a return statement in a finally block is acted on immediately on execution. I was not able to find what happens if the return statement is in the catch block. Maybe I'll try it out and see.
Welcome to JavaRanch, Ben! But what about a return statement in the finally block, will that be executed or not? Note that a very good answer to this question (and others of its type) could be discovered by simply writing a small test program and observing what happens.
[Going a bit off-topic] As an old system programmer type, I would warn that if a language question is not answered in the definitive documents, there is a risk in trying it out and relying on the result. You may wind up with an implementation-dependent program. If there is no clear language rule on the action of a return statement in a catch block, the actual result may be the unintended consequence of a particular compiler or jvm design. A future release or different product may give a different result. If this configuration is not in the test suite, the difference will only show up in your program. Of course, if lots of programmers rely on it, the difference will show up in beta testing. Whether that is remedied depends mostly on how much fuss is raised and how hard it is to conform to the older code. My favorite example is the wide use of undefined instructions on the old IBM 1401. When the IBM 360/30 came out with a 1401 emulator, IBM was forced to implement the undefined instructions. They even published a manual documenting these instructions. But it is still not best practice to rely on the undocumented behavior of a product.