Sunday, June 23, 2013

Gracefull error handling with a global exception handler




Every published C# application should have graceful error handling. Here I show you the implementation of a global exception handler using ThreadExceptionEventHandler.

First, you have to add System.Threading to both your Program.cs and Mainform.cs:
// Program.cs and Mainform.cs
using System.Threading;

Then add an event handler to Application.ThreadException:
// Program.cs
// static class Program {
//  private static void Main(string[] args) {
Application.ThreadException += new ThreadExceptionEventHandler(MainForm.MyExceptionHandler);
// Application.Run(new MainForm());

Or, if you are writing a console app, add an event handler to AppDomain.UnhandledException:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyExceptionHandler);

Then add the exception handler body:
// Mainform.cs
public static void MyExceptionHandler(object sender, ThreadExceptionEventArgs e)
{
   MessageBox.Show(e.Exception.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}

The example here simply shows a message box, but an even more graceful approach would be to log all the unhanded exceptions to a log file. That way, the errors are transparent to the user, but the developer still has access to detailed debug information.

Here is the full code:
Program.cs
MainForm.cs