aspose file tools
The moose likes Java in General and the fly likes Return Statement and Finally Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Return Statement and Finally" Watch "Return Statement and Finally" New topic
Author

Return Statement and Finally

vasansrini arumugam
Greenhorn

Joined: Nov 02, 2009
Posts: 8
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: 285

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
vasansrini arumugam
Greenhorn

Joined: Nov 02, 2009
Posts: 8
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Return Statement and Finally
 
Similar Threads
Exception Handling
952739444280 why?
Exception handling in Junit
try, catch,finally
try catch block