Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dispose an IDisposable object if the using statement throws an exception?

How can I make sure in the following code snippet that IDataReader is disposed of if ExecuteReader throws an exception?

using (IDataReader rdr = cmd.ExecuteReader())
{
    // use it
}

It makes sense to me that the using syntatic sugar does not call Dispose (since there is no instance to call it on). However, how can I be sure that the scarce resources that are normally allocated by classes that implement IDisposable will be releases?

like image 655
jpoh Avatar asked Dec 08 '22 07:12

jpoh


1 Answers

If ExecuteReader, in your example, throws an exception it never returns anything. It is then up to the implementation of ExecuteReader to dispose of anything created before the exception.

like image 130
sisve Avatar answered Jan 11 '23 22:01

sisve