2008-12-02

Try...Catch in WinForms Main() method not Catching

Had a really bizarre and annoying error. I had a .Net WinForms app that started with a code block like this:

[STAThread]
static void Main() {
   try {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new MDIFormMain());
   } catch (Exception ex) {
      using (FormShowException showException = new FormShowException()) {
         showException.Display(ex);
      }
      Application.Restart();
   }
}

The only problem was, after one exception caused a restart (which had a side-effect of detaching the debugger), every other exception would throw a standard .Net "unhandled exception" box. Huh?

The right combination of Google search terms finally brought me to this page. Yes, apparently the above construct is fine running in a debugger, but not so much in stand-alone.

The solution, as described on the referenced page, is instead of using try...catch, bind to the Application.ThreadException event (which works both with and without a debugger attached), like so:

[STAThread]
static void Main() {
   Application.EnableVisualStyles();
   Application.SetCompatibleTextRenderingDefault(false);
   Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
   Application.Run(new MDIFormMain());
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e) {
   using (FormShowException showException = new FormShowException()) {
      showException.Display(e.Exception);
   }
   Application.Restart();
}

Very simple fix for a very aggravating little problem. Thank you, Craig Andera.

No comments: