Thursday, June 23, 2005

Global error handling for Windows applications in .NET

Just had a situation where there was a need for a global error handler method for windows applications in .NET. This handler should be invoked whenever there is an unhandled error raised in the windows application.
A way to do this is handling the ThreadException event of the Application object.

For example:
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
 Application.ThreadException+=new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
 Application.Run(new Form1());
}

private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
 MessageBox.Show(e.Exception.ToString());
}

Maybe there are other methods of doing this as well. But for a single threaded application this seemed ok.

No comments: