[Journal - Anonymous Methods and Exceptions]

Anonymous Methods and Exceptions

Wednesday, February 22, 2006

I have outed myself on believing that event handlers are not only to handle events, but should also handle any exceptions that pop up.

Well, with all the handiness of anonymous methods, that rule is easy to forget:

private void InitListView(){
    try{
        ListView lvw = new ListView();
        lvw.SelectedIndexChanged += delegate{
            btnEdit.Enabled = (lvw.SelectedItems.Count == 0);
        }
    }catch(Exception ex){
        // ...
    }
}

Suppose an exception is thrown in the anonymous event handler. Let's look at the call stack:

Form1.InitListView.AnonymousMethod()
[External Code]
Form1.Form1()
[External Code]	
Program.Main()

Clearly, the try-catch block in InitListView isn't going to be very helpful here, because InitListView() is not on the stack. The exception goes up all the way to Main(). Up there, it's way too late to catch the exception.

So don't forget that everything that applies to handling exceptions in event handlers applies to anonymous event handlers, too.