File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Finally block Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Finally block" Watch "Finally block" New topic

Finally block

SJ Rao

Joined: Mar 05, 2003
Posts: 25
In the below example is finally block executed as there are return statements in try & catch block ?
return a;
catch (Exception e)
return b;
return c;
Shridhar Dhoopad

Joined: Apr 16, 2000
Posts: 5
Java's finally block provides a mechanism that allows your method to clean up after itself regardless of what happens within the try block. Use the finally block to close files or release other system resources.
SJ Rao

Joined: Mar 05, 2003
Posts: 25
But in this case, is the finally block executed as there are return statements in try / catch block ? Does it still execute finally block ?
This was one of my interview questions.
Wayne L Johnson
Ranch Hand

Joined: Sep 03, 2003
Posts: 399
The finally block is guaranteed to execute regardless of what happens in the "try{ }" and "catch{ }" blocks. The only exception is if the application shuts down, either with an unrecoverable error (Java out-of-memory exception) or an explicit "System.exit()" call.
Try the following code:

The output in both cases is "3", meaning that the "finally" block was executed last and it's return was honored. This will give you a warning message when you compile it, but it does compile and run. The first call to "ugly" throws an exception (Integer divide by zero) and ends up in the "catch" block. The second call to "ugly" works correctly. But both "deferred" to the "finally" block's return.
Needless to say, this is *ugly* programming of the highest order and should be avoided at all cost.
As a general note, you can always figure out what Java actually does by writing a simple program and seeing what the results are ;-)
[ October 29, 2003: Message edited by: Wayne L Johnson ]
I agree. Here's the link:
subject: Finally block
Similar Threads
understanding try-catch block?
Try an Finally Working Confusion
Statement not reachable??
about exception handling
Unreachable statement