Should you implement IDisposable.Dispose() so that it never throws?

The Framework Design Guidelines (2nd ed) has this as (§9.4.1):

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

Commentary [Edit]:

  • There are guidelines, not hard rules. And this is an “AVOID” not a “DO NOT” guideline. As noted (in comments) the Framework breaks this (and other) guidelines in places. The trick is knowing when to break a guideline. That, in many ways, is the difference between a Journeyman and a Master.
  • If some part of the clean-up could fail then should provide a Close method that will throw exceptions so the caller can handle them.
  • If you are following the dispose pattern (and you should be if the type directly contains some unmanaged resource) then the Dispose(bool) may be called from the finaliser, throwing from a finaliser is a bad idea and will block other objects from being finalised.

My view: exceptions escaping from Dispose should only be those, as in the guideline, that as sufficiently catastrophic that no further reliable function is possible from the current process.

Leave a Comment