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

c#, dispose, exception, idisposable

Solution

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.

Problem

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?

Original source