aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Use of finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Use of finally" Watch "Use of finally" New topic
Author

Use of finally

Shashank Sharma
Ranch Hand

Joined: Sep 27, 2006
Posts: 91


Hi all,
This is a silly question I am putting here ,I got confused with the basic try catch logic;
please check the code I wrote above.

it gives output 1234
and if I remove finally block from above code ,output is 124.

As far as I remember finally is used to execute important code(cleanup ,message to user etc..) even if there is an exception.
but above code print 4 in both the cases (with /without finally).then whats the use of finally .

guys I think I am missing very basic concept of exception handling. please help.


Thanks



Ikpefua Jacob-Obinyan
Ranch Hand

Joined: Aug 31, 2010
Posts: 394

Hello Shashank, well you placed a println statement in the finally block and it executes the statement and displays 3 in the output as expected.

In java when you handle an exception, the program executes to completion. Why?...well simply because the catch block took care of the problem and it was NOT propagated to the main method to provoke a JVM shut down. HTH.

Regards

Ikpefua


OCPJP 6.
In Your Pursuit Towards Certification, NEVER Give Up.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18155
    
    8

The finally-block is guaranteed to execute no matter whether an exception was thrown in the try-block or in the catch-block. Try this code and it will show you why it makes a difference:

And then try this code:
 
jQuery in Action, 2nd edition
 
subject: Use of finally
 
Similar Threads
confused about the output of the program on exceptions?
Enthuware questions
Try/catch/finally
Why is 5 getting printed here?
exception..try catch block execution