Recent Articles

Global Catch All Exception in .NET Winform and Console Application

As a good programmer, you normally want to catch all exceptions at the highest tier in code so that your program has the chance to display the error message to the user or log it to the appropriate location. Under ASP.NET, you can do so easily by overriding the Application_Error event in Global.asax file.

protected void Application_Error(Object sender, EventArgs e)
{
 Exception ex = Server.GetLastError();
 
 // Perform error logging here...

 // Clear the error and maybe redirect to some other page...
 Server.ClearError();
}

Unfortunately, there is no concept of Global.asax in a winform or console application in .NET. In a windows form application, the equivalent global catch all is available by listening to the ThreadException and AppDomain UnhandledException events.

[STAThread]
static void Main()
{
 // Catch all unhandled exceptions
 Application.ThreadException += new ThreadExceptionEventHandler(ThreadExceptionHandler);

 // Catch all unhandled exceptions in all threads.
 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);

 Application.Run(new MainForm());
}

private static void ThreadExceptionHandler(object sender, ThreadExceptionEventArgs args)
{
 try
 {
  // Log error here or prompt user...
 }
 catch { }
}

private static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
 try
 {
  // Log error here or prompt user...
 }
 catch { }
}

The event model is slightly more complicated in a winform application because you typically have more than one thread that you hand manage unlike in ASP.NET where threads are shielded from you in the form of page requests. Other than that, just implementing these two events will get you out of a lot of trouble and helps find those nasty runtime bugs. Have fun!