Question

We use try catch block in our code. What I want to ask here is that using finally block is a good practice. I haven't seen much finally block in code. Is it bad practice?

Was it helpful?

Solution 2

If you are doing any database operation in your program, then finally block is good choice. So,Using finally block here, It closes database automatically. For example:

try
{
 //code of operation
}
catch(Exception error)
{ //code to handle exception
  error.printStackTrace();
}
finally
{ //any code which need to execute mandatory   
  commit();
  db.close();
}

In the above example, try block handles the opening DB connection and inserting,retrieving or updating the DB. catch block handles exception and finally block close all DB connection.

OTHER TIPS

Catch : When something goes wrong.
Finally : When something / nothing goes wrong.

Finally blocks are there to help you out when you want to do something even when the exception is thrown or not. Like closing database connection, releasing resources. You cant do this in catch block as catch are only executed when exception is thrown.

Q: When to use try-catch?
Ans: You want to do something when exception is thrown

Q: When to use try-finally?
Ans: You want to do something even when exception is thrown or not.

Q: When to use try-catch-finally?
Ans: When you want to something x only when exception is thrown and something y when exception is thrown or not.

To summarize this

try{  

//.....

}
catch{  
   // Something you want to do only when exception is thrown
   // Like OMG evil execption RUN RUN
}  
finally{
   // Something you want to do even the exception is thrown or not  
   // Like who the hell cares about exception
}

It is certainly good practice if you need to handle an exception and still have to execute some code (typically cleaning up, disposing of resources) in case of an error.

Quoting from "Best Practices for Handling Exceptions" (http://msdn.microsoft.com/en-us/library/seyhszts(v=VS.71).aspx):

Use try/finally blocks around code that can potentially generate an exception and centralize your catch statements in one location. In this way, the try statement generates the exception, the finally statement closes or deallocates resources, and the catch statement handles the exception from a central location.

Using finally is good practice. It will be executed irrespective of the exception occurs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top