Coding with passion

首页 新随笔 联系 订阅 管理

When developing windows/console applications using .Net, it is recommended to catch the following two exceptions:

  • AppDomain.CurrentDomain.UnhandledException
  • Application.ThreadException

If there are some uncaught exceptions raised in a app-domain, the system default handler will report the exception and terminates the application by default. And if raised in a thread, the thread may be blocked. Catching UnhandledException and ThreadException events provides us a way of creating robust applications.

The following code segements demonstrate how to make use of the two events:

static void Main()
{
  try {
   // Setup unhandled exception handlers
   AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);

   // Unhandled Forms exceptions will be delivered to our ThreadException handler
   Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(AppThreadException);

   // Other code
   ....
  }
  catch( Exception e ) {
    ....
  }
}

/// <summary>
/// CLR unhandled exception
/// </summary>
private static void OnUnhandledException(Object sender, UnhandledExceptionEventArgs e)
{
  HandleUnhandledException(e.ExceptionObject);
}

/// <summary>
/// Displays dialog with information about exceptions that occur in the application.
/// </summary>
private static void AppThreadException(object source, System.Threading.ThreadExceptionEventArgs e)
{
  HandleUnhandledException(e.Exception);
}

private static void HandleUnhandledException(Object o)
{
  Exception exp = o as Exception;
  MessageBox.Show(exp.Message, "Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);

  Application.Exit(); // Shutting down
}
posted on 2007-08-27 22:13  Kellin  阅读(382)  评论(0编辑  收藏  举报