Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > finally block consumes/stifles exception

Reply
Thread Tools

finally block consumes/stifles exception

 
 
Steve Claflin
Guest
Posts: n/a
 
      02-13-2006
I was rather surprised at the outcome of this code, which I created to show
someone how a finally block will run even if the try or catch block returns
from the method:



 
Reply With Quote
 
 
 
 
Loveen
Guest
Posts: n/a
 
      02-13-2006
Hi
Take this example...

public class DebugFinally {
public static void main(String[] args) {
try{
int number = Integer.parseInt("1245");
}catch(Exception ex){
System.out.println("In Catch");
return;
}finally{
System.out.println("In Finally");
}
System.out.println("Not Returned");
}
}

Output:
In Catch
In Finally

As you see above the program performed what was written in Catch but
after that it directly goes to finally block and execute what ever is
written in it, after that it comes back to the catch block to call the
return.

Basically internally the compiler executes whatever is written in the
finally block before executing any statement which takes the control
out of try/catch construct.

But, there is one exception to this. If I call System.exit(0); in place
of return then, program would end abruptly without giving care to
whatever is written in finally block.

And in that scenario the output would be modified as follows:

}catch(Exception ex){
System.out.println("In Catch");
System.exit(0);
}finally{
System.out.println("In Finally");
}

Output:
In Catch

 
Reply With Quote
 
 
 
 
Rhino
Guest
Posts: n/a
 
      02-13-2006

"Steve Claflin" <(E-Mail Removed)> wrote in message
news:eK_Hf.2468$Lr.1851@trnddc01...
>I was rather surprised at the outcome of this code, which I created to show
>someone how a finally block will run even if the try or catch block returns
>from the method:
>

Maybe you'd like to try again? This time _with_ a code fragment?

--
Rhino


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Try...Catch...Finally not firing finally? David Lozzi ASP .Net 12 05-11-2007 12:41 AM
Exception in finally block Efi Merdler Java 15 12-04-2006 06:27 PM
Fo:Block can you check to see if a block contains any text by using the block id? morrell XML 1 10-10-2006 07:18 PM
finally block in Exception Matt Java 4 07-01-2004 04:28 AM



Advertisments