Handle uncatched exception in Windows Form Application

The core code is:
Application.ThreadException += 
 
new ThreadExceptionEventHandler(ApplicatioThreadExceptionHandler); 

Two notes:

1. The handler needs to be set up BEFORE the Windows message loop is constructed.
This means it needs to be before Application.Run(MainForm). If you are showing a
splash screen at start up, or even a ‘Do you want to upgrade to the new version?’
form before calling Application.Run, you need to put your
Application.ThreadException += new ThreadExceptionEventHandler(… statement
before the code to do those things is called.

2. The handler is not in force until the initialization of your main form has completed.
Any exception in the constructor of the main form, or in any code you execute prior
to Application.Run(MainForm) will not be handled by the top-level handler. Of course,
putting complex initialization code in the constructor of a form is a bad idea in general,
 not least because it gets run by the designer when you open the form in Visual Studio.
However, this does mean that you may need a try..catch block around any initialization code
 that runs before the main form is launched in case it throws an exception.

Referred from Top-level Exception Handling in Windows Forms Applications
posted @ 2007-11-27 13:49  Easoney  阅读(362)  评论(0编辑  收藏  举报