Why to use "finally" block in C#?
By using a finally block , you can clean up any resources that are allocated in a try block, and you can run code even if an exception occurs in the try block . It is just to ensure releasing of all the valuable resources even if the code executed correctly or with an exception. The execution of a finally block is intended to release resources , such as database connections, which are usually available in limited quantities.
The code inside a finally block will get executed regardless of whether or not there is an exception. The "finally" block is very useful in various situations, particularly when you need to perform cleanup (dispose resources), though a using block is often better in this case. One important thing to remember is, a finally block MUST NOT throw an exception unless the system design explicitly wants you to do so, which is considered bad practice in general. C# also contains the using statement , which provides same functionality for IDisposable objects in a convenient manner.
- What are the Default Access Modifiers in C#?
- What is a sealed class in C#?
- What is operator overloading in c#?
- Difference Between Finalize and Dispose Method in C#?
- What is an Object Pool in .Net?
- What is Anonymous type in C#?
- Dynamic type variables Vs Object type variables in C#?
- What is the difference between Array and ArrayList in C#?
- Difference Between Clone() and CopyTo() Array
- Difference between throw and throw new Exception() in C# ?