| 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.
|
 |
 |
|
|
subject: Return Statement and Finally
|
|
|