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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With