• Post Reply Bookmark Topic Watch Topic
  • New Topic

"return" inside the try-catch-finally  RSS feed

 
Kaustubh Patil
Ranch Hand
Posts: 164
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
i am confused about the way the return works ...
say if i have a return in the try block and something in the finally..
this is the prog..

the following gets printed..
----------------------
in try ii =1
inside finally..ii = 2
in main ii = 1
-----------------------
now the question is ..
The return should give the control back to the calling procedure..
But i do not see it happening here. The control is returned (i guess) to the main the vaule of ii is printed as 1 and then the ii++ takes place and the statement in the finally is executed..
How does this happpens..Does it mean that the statements in the finally get executed after the return ? if not then whats the logic..??
Thanks in advance...
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The finally block gets to execute last - even if the try or catch block returns. Note that the return value of the try or catch block would not be used if the finally block were to return (which it does not have to do if the try or catch blocks have already done so). Of course, if the try or catch block were to throw an exception or close the JVM, then the finally block might not get a chance to execute.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Dirk Schreckmann:
Of course, if the try or catch block were to throw an exception or close the JVM, then the finally block might not get a chance to execute.

I think the semantic of a finally block is to *always* get executed before controll is given back to the caller, no matter what.
A killed JVM might be an exception, of course... :roll:
 
Michael Ernest
High Plains Drifter
Sheriff
Posts: 7292
Netbeans IDE VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the try/catch/finally construct is a derivative of C++, which in turn derives this feature from 'jump' instructions that appear in ISO C as setjmp() and longjmp(). These in turn derive from CPU instructions by the same name, but that's drilling a bit deep.
In short, each of these constructs alters the expected trace of bytecode instruction processing. The bytecode that are invoked by finally are defined to precede any return instruction that might occur in try or catch.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!