I have used try-catch/except-finally variants in many languages for years, today someone asked me what is the point of finally and I couldn't answer.
Basically why would you put a statement in finally instead of just putting it after the whole try-catch block? Or in other words is there a difference between the following blocks of code:
try{ //a}
catch {//b}
finally {//c}
try{//a}
catch{//b}
//c
EDIT:
PEOPLE, I know what finally does, I have been using it for ages, but my question is in the above example putting //c
in finally seems redundant, doesn't it?
The purpose of a
finally
block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone:try
block exits viareturn
catch
block either rethrows the caught exception, or--accidentally or intentionally--ends up throwing a new one.try
block encounters an exception for which there is no catch.One could copy the
finally
code before everyreturn
or throw, and wrapcatch
blocks within their own try/catch to allow for the possibility of an accidental exception occurring, but it's far easier to forgo all that and simply use afinally
block.BTW, one thing I wish language designers would include would be an
exception
argument to thefinally
block, to deal with the case where one needs to clean up after an exception but still wants it to percolate up the call stack (e.g. one could wrap the code for a constructor in such a construct, andDispose
the object under construction if the constructor was going to exit with an exception).Finally block is executed even if an exception thrown in the try block. Therefore, for instance if you opened a stream before, you may want to close that stream either an exception is thrown or not. Finally block is useful for such an issue.
Finally
make sure your code is executed even if you get an exception.The finally block is useful for cleaning up any resources allocated in the try block as well as running any code that must execute even if there is an exception
http://msdn.microsoft.com/en-us/library/zwc8s4fz(v=vs.80).aspx