Global Exception Handler in WinForms

This is a small code snippet to set the global exception handler in Windows Forms application.

Setting a global exception handler can help us in logging the exceptions to a common file, show them to the user in a friendly way or email to the moderator.

// Place the code inside Program.cs, before Application.Run

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

 

public static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
    // Process the e.Exception
    MessageBox.Show("I got the exception!");
}

Leave a Reply

Your email address will not be published. Required fields are marked *