“Icky” Decisions
@KeithDahlby posted a good question for thought the other day on “the” Twitter:
When implementing the Observer pattern, how do you handle exceptions from observers?
This seemingly harmless question should spark at least a good 15 minute debate. An obvious question (and the one I asked):
Do you care if an observer throws an exception?
If you consider the classic observer pattern you’ll note that the observed only knows about it’s observers through an interface. Using an interface for observers to reduce coupling is a good practice but by doing that you’ll want to be sure to retain that reduction of coupling by not allowing the observed to know about any of the concrete observers.
Deciding to allow the observed to know about it’s observers and allow it to handle exceptions would introduce coupling that could lead to bugs down the road.
Keith is a super smart guy and knew all along what to do, but the “what” is icky:
That’s what we’re doing, but agreed that it’s icky – wish there were a better option that catch(Exception)
This is icky because in the event an observer is very broken you won’t have a first-hand way to find out (and ReSharper will let you know about the dangers of your empty catch block). Each observer is now responsible for logging or notifying someone about exceptions which adds some additional complexity (possibly through configuration or another mechanism).
You’ll run into these icky decisions and each one certainly needs healthy debate and some documentation to cover the bases later on when someone might question why the icky option was chosen.
What was your most recent “icky” situation?
Comments are closed.


March 12, 2010 - 8:27 am
catch(Exception ex)
{
_log.Error(“Consumer Exception not caught.”, ex);
}
At least they can learn something from this, compared to eating the exception without even a burp.
And you should catch per event consumer, not a global one because an early failure would prevent other consumers from know about the event.
Not that I have any experience with any of this stuff.
March 12, 2010 - 8:31 am
Yeah, from the guy who works on some event-driven service bus thingy. It’s a tough call and one I’ve made a few times too. Not ideal for sure.
March 13, 2010 - 10:12 pm
I completely agree with Chris that a logged exception is preferable to an empty catch{}. And of course observers should do all they can to avoid throwing in unexceptional circumstances.
In my view, the ickyness isn’t so much that the observer has to observe “with caution”, but that there’s not really a good mechanism to catch bad but not fatal exceptions – if my observer throws an OutOfMemoryException, is that really something I can recover from? As with all things, the answer is “it depends”, but worth some thought.
It’s also worth pointing out that catch(Exception) is changing in .NET 4 to not catch “process corrupting” exceptions by default. http://bit.ly/adlDjg