Net-informations.com
SiteMap  | About    

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.

Example

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.









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.