aspose file tools*
The moose likes Beginning Java and the fly likes Return Statement from a Method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Return Statement from a Method" Watch "Return Statement from a Method" New topic
Author

Return Statement from a Method

PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212


If a Method is suppoused to return a Value , the return value should be always in a finally block ? Am i correct on this ?


John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
No, you generally don't need to put return values in finally blocks. Finally blocks are usually used for resources that need to be released, such as closing files or database connections. Your method could easily be rewritten as:

PavanPL KalyanK
Ranch Hand

Joined: Feb 28, 2009
Posts: 212
John Thanks ,

If its a simple what you said would be fine . But if i am dealing with any Data Base connections then i should be dealing with the try and catch blocks in that case i am asking.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11406
    
  16

One of the reasons/purposes of having a try/catch/finally block is to separate out error handling from the normal flow of your code. the normal operation goes in the 'try', the error goes in the 'catch', and the 'i really need to clean up' goes in the 'finally'.

Since the return is part of the normal flow, it could go in either the 'try' or outside of the try/catch block all together. some folks argue that the ONLY think that should go in the try is stuff that can throw the exception, and your return statement is not one of them.



There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19719
    
  20

You should even be careful about returning values from finally. For example:

The above code will print 5, not 1.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Chuck Mondi
Ranch Hand

Joined: Oct 14, 2008
Posts: 31
Whatever you place in Finally will run regardless of what happens as a result of your try/catch block so only put code in the finally block that you always want to run.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Return Statement from a Method