Monday, October 23, 2006

For a long time now I have been wondering how to handle a situation in which there is an unhandled exception thrown from the event handling method of my events. Given the simple pattern for raising events in the form of:

private event EventHandler SomeEvent;
protected void OnSomeEvent()
{
   
if (SomeEvent != null)
   {
      SomeEvent();
   }
}

What happens when one of the handlers of SomeMethod throws exception? Keeping in mind the internal implementation of events that I have described here, I know that this exception will go outside the SomeEvent() call and even outside the OnSomeEvent() up the call stack. It is rather obvious. What is not so obvious is one should handle such a situation?

I have spend some time searchin the Internet for some kind of guideline or best practice but I have been unable to find one. I have talked with Krzysztof Cwalina about it and it seems that there is no good solution to the problem. You can put the event invocation in the try catch block but the only kind of exception you can catch there is really the Exception - since you don't know anything about what the handler may be. Krzysztof suggests that it may be good idea to document what kind of exception you expect from the event handlers but it it only a partial solution. Other solutions include terminating the application, allowing the exception to propagate or swallowing the exception - none of those seems right to me.

If any of you knows of any proven practice on how to handle this kind of situation I would really appreciate it if you point me in the right direction.

kick it on DotNetKicks.com