C# 捕捉未被Try Catch捕获的异常

  • Winform程序中,有try…catch…进行异常捕获,但还是存在异常关闭的情况,在程序中捕获这些异常,会大大方便问题的定位分析与程序优化。

两个异常事件

  • Application.ThreadException在发生应用程序UI主线程中未捕获线程异常时发生,触发的事件;
  • AppDomain.CurrentDomain.UnhandledException当后台线程中某个异常未被捕获时触发;

添加步骤

  • 程序入口(Main)添加事件绑定

          //设置应用程序处理异常方式:ThreadException处理
          Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
          //处理UI线程异常
          Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
          //处理非UI线程异常
          AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
  • 添加事件实现、异常信息解析

      private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
      {
          string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
          // 后续处理,保存或输出
      }
    
      private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
      {
          string str = GetExceptionMsg(e.Exception, e.ToString());
          // 后续处理,保存或输出
      }
    
      static string GetExceptionMsg(Exception ex, string backStr)
      {
          StringBuilder sb = new StringBuilder();
          sb.AppendLine("****************************异常文本****************************");
          sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
          if (ex != null)
          {
              sb.AppendLine("【异常类型】:" + ex.GetType().Name);
              sb.AppendLine("【异常信息】:" + ex.Message);
              sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
    
              sb.AppendLine("【异常方法】:" + ex.TargetSite);
    
          }
          else
          {
              sb.AppendLine("【未处理异常】:" + backStr);
          }
          sb.AppendLine("***************************************************************");
          return sb.ToString();
      }
    

猜你喜欢

转载自blog.csdn.net/m0_37447148/article/details/88797757
今日推荐