Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling-Purpose of finally in the try-catch construct

 
ShrutiRavi Gupta
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of finally if the code after the try-catch still gets executed. Whatever we put after the try-catch gets executed irrespective of whether an exception was thrown or not. so should that code be placed in finally?


 
Rob Spoor
Sheriff
Pie
Posts: 20546
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
With finally, the code will be executed even if the try or catch block will exit your method. This could be because of a return statement, or an exception you don't expect (RuntimeExceptions mostly, or exceptions your method are declared to throw). This makes finally blocks excellent for closing streams, database connections or anything else that takes up valuable resources.
 
Balagopal Kannampallil
Ranch Hand
Posts: 136
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take this example of a simple database operation in java

You can argue like why can't you call the conn.close() in the try statement itself, why using a finally block to close the connection. What happens if the line before conn.close() call throws an exception in the try block? It will directly go to the catch statement without closing the connection which we opened. Th connection will remain open like that until the object gets garbage collected. Is it a good practice to do so? No right?
So using a finally block will ensure that no matter whatever happens in the try and catch block- The connection which you opened will be closed.
 
ShrutiRavi Gupta
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot. that makes sense.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49382
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was a nice explanation, yes. You know about the section in the Java Tutorials, I presume?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic