Jul 1, 2012

Catch Unhandled Thread Exceptions

1 comment
This example shows how to manage all exceptions that haven't been caught in the try-catch blocks (in Windows Forms application).

The UnhandledException event handles uncaught exceptions thrown from the main UI thread. The ThreadException event handles uncaught exceptions thrown from non-UI threads.

Code:
static void Main()
{
  Application.EnableVisualStyles();
  Application.SetCompatibleTextRenderingDefault(false);

  Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

  Application.Run(new Form1());
}

static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
    // here you can log the exception ...

  MessageBox.Show(e.Exception.Message, "Unhandled Thread Exception");
}

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
   // here you can log the exception ...

  MessageBox.Show((e.ExceptionObject as Exception).Message, "Unhandled UI Exception"); 
}

1 comment :