• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return of the try-catch

 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if i put a return in the try it will come out from that even
without executing finally.but at catch block if i put return
finally get executed.
1)what return does in both cases?
2)why both differs in it's cource?
thank you,
JYOTHI ABRAHAM
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you execute a return in a try block, the code in the corresponding finally block WILL be executed.
 
jason adam
Chicken Farmer ()
Ranch Hand
Posts: 1932
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree, everything I've read or learned states finally always is executed.
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there is always System.exit()...
 
Peter Haggar
author
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A return, break, or continue(that exits a try block) stmt will cause execution to always go to the finally block. The only case where you can enter a try block, and not execute its finally is if there is a System.exit() in the try block.
Peter Haggar
------------------
Senior Software Engineer, IBM
author of: Practical Java
 
jyothi abraham
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanx a lot, Sirs.
I have a doubt on following program;
a)
class Exceptions1
{
public static void main(String args[])
{
System.out.println("A");
try
{
return;
}
catch(Exception e)
{
System.out.println("B");
// return;
}
System.out.println("C");
}
O/P of (a) prints A only.not C.If it just exit from scope ,C
also to be printed.Here it is not happening.why?
Thank you,
JYOTHI ABRAHAM
 
Michael Fitzmaurice
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Put c inside a finally block and it will execute. It will never execute as is since you are returning from the try block. The sequence in this case would be:
-check for exception thrown (if so, execute any relevant catch block)
-look for & execute finally block
-if no execption was thrown, return
So, any code after the return in the try block will NOT execute, unless its inside a finally block, in which case it will always execute (except for in the case of power loss, System.exit. etc.).
I think the difficulty you are having here also requires you to fully understand what the return key word means. Read a bit more about this and experiment with what happens when you place a return statement inside a method at various points.
------------------
"One good thing about music - when it hits, you feel no pain"
Bob Marley
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic