Gotcha Exception in Dispose method masking other errors in Using blocks

suggest change

Consider the following block of code.

try
{
    using (var disposable = new MyDisposable())
    {
        throw new Exception("Couldn't perform operation.");
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

class MyDisposable : IDisposable
{
    public void Dispose()
    {
        throw new Exception("Couldn't dispose successfully.");
    }
}

You may expect to see “Couldn’t perform operation” printed to the Console but you would actually see “Couldn’t dispose successfully.” as the Dispose method is still called even after the first exception is thrown.

It is worth being aware of this subtlety as it may be masking the real error that prevented the object from being disposed and make it harder to debug.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Using Statement:
* Gotcha Exception in Dispose method masking other errors in Using blocks

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
58 Using Statement
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script