Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actual use of finally block

I asked to my friend about this question, he said that it is used for destroying the object created during the exception handling. But in c# GC is there for destroying such kinds of unused objects, then what is the actual use of finally block. Tell me with a scenario related to that.

like image 560
Jibu P C_Adoor Avatar asked May 20 '10 07:05

Jibu P C_Adoor


2 Answers

It is a block that is guaranteed to run whether or not an exception occurs.

So typically, you would use it if there is some sort of resource that you want to ensure is properly released. Nothing to do with objects created during the exception handling. But say you had a connection of some kind to a database, or a file handle.

If it's a managed object that implements IDisposable, a better approach is normally the using keyword.

like image 131
David M Avatar answered Oct 19 '22 03:10

David M


The GC will clear managed resources (objects your application has created in memory) when they are no longer referenced. This doesn't include things like file handles, network resources, database connections etc... You must clear them up yourself in the finally block or risk them not clearing (although most will clear eventually).

OR, more commonly:

Many classes which which unmanaged resources to be disposed of implement the IDisposable interface. This means you can wrap the code in a using block and be sure that the unmanaged resources will be cleared (it calls the object's Dispose() method when it goes out of scope).

A good example of using the finally block is when you use an Office interop library. Say you open Microsoft Word, run some code, code fails...Word will always need closing regardless of whether an error occurred or not. Therefore I would put the closing code in the finally block.

like image 35
David Neale Avatar answered Oct 19 '22 04:10

David Neale