This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Exception Handling-Purpose of finally in the try-catch construct Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exception Handling-Purpose of finally in the try-catch construct" Watch "Exception Handling-Purpose of finally in the try-catch construct" New topic
Author

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

ShrutiRavi Gupta
Greenhorn

Joined: Jan 08, 2009
Posts: 8
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?



Shruti
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Balagopal Kannampallil
Ranch Hand

Joined: Oct 18, 2004
Posts: 136

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.


SCJP 5.0 and now fighting with ExtJS
ShrutiRavi Gupta
Greenhorn

Joined: Jan 08, 2009
Posts: 8
thanks a lot. that makes sense.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37884
    
  22
That was a nice explanation, yes. You know about the section in the Java Tutorials, I presume?
 
 
subject: Exception Handling-Purpose of finally in the try-catch construct
 
Similar Threads
Exception in finally
try-catch-finally
Need for finally block?
Confusion in Exception Question from Marcus Green Exam 1
Exception Debug issue for return