Skip to content

Should Dispose throw exceptions?

by Alex Peck on November 19th, 2009

The Framework Design Guidelines suggest that you should avoid throwing an exception from Dispose. This page has a better quote:

Avoid throwing an exception from within Dispose except under critical situations where the containing process has been corrupted (leaks, inconsistent shared state, etc.).

I can think of two good reasons to avoid throwing (depending on your use case they may or may not represent the desired behaviour):

  • If there is an unhandled exception in the finaliser thread, under .NET 2.0 and above, the process terminates. Yikes. As MSDN states, IDisposable classes should call Dispose from the finaliser to be sure Dispose is always called.
  • Exception masking: If dispose is triggered by a using block after an exception is thrown inside the block, then Dispose throws, you will get the exception from dispose, not the original.

Rogue Dispose methods pop up in the .NET framework (e.g. in WCF), and in other libraries. If you have to contend with some dangerous disposal, Marc Gravell has a safe IDisposable wrapper template/extension method pattern. This could easily be modified to do some logging rather than silently swallowing.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS