This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
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?
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.
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.