It's not a secret anymore!
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Use of finally" Watch "Use of finally" New topic

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.


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.



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

Joined: Oct 14, 2005
Posts: 19973

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:
I agree. Here's the link:
subject: Use of finally
It's not a secret anymore!