This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Return Statement and Finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Return Statement and Finally" Watch "Return Statement and Finally" New topic
Author

Return Statement and Finally

srini arumugam
Greenhorn

Joined: Nov 02, 2009
Posts: 14
Return Statement: - The last control statement in a method is return. It causes program control to transfer back to the caller of the method. It immediately terminates the method in which it is executed.

Finally: - The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

But in the below code, even though the compiler hits the return statement in catch block the control immediately does not go back to the caller function. It executes finally block, increments i and then the return happens from the finally block. So the returned output for "i" is 2.



1)Why the control does not go back to caller function as soon as it hits return in catch block.
2)Is return behaving differently in "try catch finally" conditions?
Vijay Tidake
Ranch Hand

Joined: Nov 04, 2008
Posts: 146

Hi,

Finally block is going to execute in any condition whether exception occurs or not or try and catch having the return statement.



Thanks


The important thing is not to stop questioning.Curiosity has its own reason for existing.
Will Myers
Ranch Hand

Joined: Aug 05, 2009
Posts: 319

But in the below code, even though the compiler hits the return statement in catch block the control immediately does not go back to the caller function. It executes finally block, increments i and then the return happens from the finally block. So the returned output for "i" is 2.


Actually this code doesn't compile because i is out of scope in the catch and finally blocks
srini arumugam
Greenhorn

Joined: Nov 02, 2009
Posts: 14
Sorry Will, please assume "i" is declared outside of try block.
@Vijay - Thanks for the reply vijay.

P.S : More preference is given to finally than the return statement.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Return Statement and Finally
 
Similar Threads
952739444280 why?
try catch block
Exception Handling
try, catch,finally
Exception handling in Junit