File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return Statement and Finally

 
srini arumugam
Greenhorn
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 146
Hibernate Java Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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



Thanks
 
Will Myers
Ranch Hand
Posts: 372
Java jQuery Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic