If an Exception happens in Form.Paint, does anyone catch it?

In a previous post, I mentioned the old VB6 trick of deferring form work until the Form.Paint event in order to provide a (seemingly) responsive interface to the user. Well, in the .NET world there's one strange side effect when you do this. Let's say you had this code, in a solution where the startup object is Sub Main:

This is a companion discussion topic for the original blog entry at: http://www.codinghorror.com/blog/2005/01/if-an-exception-happens-in-formpaint-does-anyone-catch-it.html

I believe that the reason for this behavior is that Form_Paint events happen on a separate thread (as do button clicks, timer events, and mouse over/drag-and-drop events).

There is an event on the Application class called ThreadException that gets fired whenever an exception occurs during an event thread. If it is not handled, it shows the dialog that you mentioned, and breaks on the Application.Run() line.

The ThreadException event will give you the Exception object that was thrown, but unfortunately the only way I’ve found to make the debugger stop on an exception at the line that it was thrown on is to set all exceptions to “Break” like you mentioned above.

  • Joshua

I can’t fully agree with the comment. You see the same behavior in OnLoad() but not on a button click event handler for instance. Try this code in both OnLoad() and button click event handler:
Object obj = null;

Thank you!