Search code examples
sql.netexceptiondisposeunmanaged

Can .NET SqlConnection.Dispose() throw an exception?


Is it possible for the Dispose method of a SqlConnnection object to throw an exception? It's always shown sitting on its own in a finally block outside of the try-catch. And if a using block is equivalent to a try...finally which then calls Dispose, that would also seem to be a case when an exception thrown by Dispose would be problematic.


Solution

  • Technically it can, but it shouldn't:

    CA1065: Do not raise exceptions in unexpected locations :

    A IDisposable.Dispose method should not throw an exception. Dispose is often called as part of the clean up logic in a finally clause. Therefore, explicitly throwing an exception from Dispose forces the user to add exception handling inside the finally clause. The Dispose(false) code path should never throw exceptions, because this is almost always called from a finalizer.

    Dispose Dos and Don'ts:

    Don't throw exceptions in Dispose. Nothing should go wrong with your object calling Dispose.

    The moral of the story appears to be that an exception thrown from Dispose is a very bad thing (for some of the reasons you mentioned) and should be handled as high as possible (there's nothing you can do about it, and probably can't recover from it).