Gotcha Exception in Dispose method masking other errors in Using blocks
suggest changeConsider 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. The exception from Dispose replaces the exception from the using body, which makes the original failure harder to debug.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents