Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Use of finally

 
Shashank Sharma
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 394
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paul Clapham
Sheriff
Posts: 21319
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic