Global Application Error Handling in Windows Forms Applications
Posted on March 2, 2007 at 13:30In my current project, I would like to log all Windows Forms errors, including those that are not caught explicitly. Lacking a built-in method (like Application_Error in the Global.asax file of an ASP.net application), I needed another way to easily catch all errors. After a bit of searching, I found a solution by Craig Andera: WinForms Catch-All Exception Handling. Here is the short version:
In the main entry point for your application (found by default in the Progrsm.cs file, Main() method), add a listener for the Application.ThreadException event.
[STAThread]
static void Main() {
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form1());
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
// Handle Exception
}
This should allow you to catch all Exceptions in your application that were not caught at the source.