C#中unhandled异常处理的问题

C#中unhandled异常处理的问题

为了增强现在正在开发的系统的健壮性,需要捕获运行时出现的无法预料而且没有被处理(unhandled)的异常。查了资料后,找到了使用 Application.ThreadException 事件处理这些异常的方法,基本步骤包括,
1、为ThreadException事件添加一个处理异常的函数句柄
2、定义处理异常的函数
 例子如下:

这种方法简单易行,而且处理效率较高,可以按照用户的意图,很方便的添加处理异常理的其他功能。但我发现,如果使用第三方提供的控件时,根本不起作用,原应可能是第三方控件运行在不同的线程中。在Microsoft的帮助中也确实提到了,上面的方法只能处理主线程中未处理的异常。好了,上网查,找到了下面的方法,使用 AppDomain.UnhandledException 替代Application.ThreadException
首先需要了解的是,此时定义的事件处理函数需要在抛出异常的线程中执行,但是在主线程中给出异常提示都是在主线程中完成的,那么如何解决这个问题呢?下面的代码给出了一个比较完整的解决方案。

  1. private delegate void ExceptionDelegate(Exception x);
  2.  static private FrmMain _MainForm;
  3.  
  4.  ///
  5.  /// The main entry point for the application.
  6.  ///
  7.  [STAThread]
  8.  static void Main()
  9.  {
  10.  _MainForm = new FrmMain();
  11.  AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);
  12.  Application.Run(_MainForm);
  13.  }
  14.  
  15.  private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
  16.  {
  17.  Exception exception;
  18.  exception = e.ExceptionObject as Exception;
  19.  if (exception == null)
  20.  {
  21.  // this is an unmanaged exception, you may want to handle it differently
  22.  return;
  23.  }
  24.  PublishOnMainThread(exception);
  25.  }
  26.  
  27.  private static void PublishOnMainThread(Exception exception)
  28.  {
  29.  if (_MainForm.InvokeRequired)
  30.  {
  31.  // Invoke executes a delegate on the thread that owns _MainForms\'s underlying window handle.
  32.  _MainForm.Invoke(new ExceptionDelegate(HandleException), new object[] {exception});
  33.  }
  34.  else
  35.  {
  36.  HandleException(exception);
  37.  }
  38.  }
  39.  
  40.  private static void HandleException(Exception exception)
  41.  {
  42.  if (SystemInformation.UserInteractive)
  43.  {
  44.  using (ThreadExceptionDialog dialog = new ThreadExceptionDialog(exception))
  45.  {
  46.  if (dialog.ShowDialog() == DialogResult.Cancel)
  47.  return;
  48.  }
  49.  Application.Exit();
  50.  Environment.Exit(0);
  51.  }
  52.  }
  53.  
  54.  private void ThreadMethod()
  55.  {
  56.  throw new Exception("From new thread");
  57.  }
  58.  
  59.  private void button1_Click(object sender, System.EventArgs e)
  60.  {
  61.  Thread thread;
  62.  thread = new Thread(new ThreadStart(ThreadMethod));
  63.  thread.Start();
  64.  }

需要注意的是:
1、需要为所有的 AppDomain UnhandledException 添加一个处理
2、 UnhandledExceptionEventArgs 参数中包含一个 IsTerminating 属性,表示是否中止 common language runtime

引用通告地址: 点击获取引用地址
标签: 异常处理
评论: 0 | 引用: 0 | 阅读: 838
发表评论
昵 称: 密 码:
网 址: 邮 箱:
验证码: 验证码图片 选 项:
头 像:
内 容: