aspose file tools*
The moose likes Java in General and the fly likes Try an Finally Working Confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Try an Finally Working Confusion" Watch "Try an Finally Working Confusion" New topic
Author

Try an Finally Working Confusion

Deepak PatilPune
Greenhorn

Joined: Mar 28, 2012
Posts: 1

If i write a return statement inside try block
and that try block also has a finally block then will the finally block execute
eg: try{
return 0;
}
catch(Exception e)
{

}
finally{
System.out.println("Final Block");
} .?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4240
    
    7

Try it out, see what happens. That's by far the best approach when you've got a question like that.
Zeeshan Sheikh
Ranch Hand

Joined: Nov 20, 2011
Posts: 144

The runtime system always executes the statements within the finally block regardless of what happens within the try block.


MySQL Blog
http://mysqlearner.blogspot.com/
Dinesh Sing
Greenhorn

Joined: Mar 04, 2012
Posts: 3
The finally bock code is always executed, irrespective of anything happening inside the try block. That is the sole purpose of finally block in java.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

And once you've observed what happens, learn this rule: Never return, throw, break, or continue out of a finally block. Since finally is just for cleanup, we don't want it to change how its try statement completes.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19543
    
  16

I agree. If you need to return / throw / break etc if the try block succeeded or not, just put it after the try-catch(-finally) block.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Rob Spoor wrote:I agree. If you need to return / throw / break etc if the try block succeeded or not, just put it after the try-catch(-finally) block.


Or inside the try.

Never mind. Mis-read.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19543
    
  16

I think you missed the "or not". What I meant was returning the same value from the try and catch blocks without duplicating that code.
So instead of
use
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

Rob Spoor wrote:I think you missed the "or not".


Yup.
 
jQuery in Action, 2nd edition
 
subject: Try an Finally Working Confusion
 
Similar Threads
try/finally block
Finally block
Doubt in try finally .......
return of the try-catch
Statement not reachable??