C# Global Exception Handling

Logging Exceptions when they occur can you give you valuable information on where your code needs to be improved. We all (hopefully) know about try-catch blocks, but it can sometimes be messy trying to wrap every possible line with one. What we need is a global Exception handler to catch the Exceptions we weren’t expecting…

Luckily, there are two events we can use:

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{}

To hook them up to an existing win forms app, simply add them before the call to Application.Run():

public static void Main(string[] args)
{
  // Global error handlers
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
  Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

  Application.Run(new MainForm());
}

For more info, MSDN is your friend:

AppDomain.UnhandledException Event

Application.ThreadException Event

Advertisements
This entry was posted in Tips and Tricks and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s