C ා catch the exception not caught by Try Catch

  • In Winform program, there is try catch... Exception capture, but there is still an exception closed situation, in the program to capture these exceptions, will greatly facilitate the problem location analysis and program optimization.

Two exception events

  • Application.ThreadException an event triggered when a thread exception is not caught in the main thread of the application UI;
  • AppDomain.CurrentDomain.UnhandledException is triggered when an exception in the background thread is not caught;

Adding steps

  • Add event binding to program entry (Main)

          //Set application handling exception method: ThreadException handling
          Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
          //Handle UI thread exceptions
          Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
          //Handle non UI thread exceptions
          AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
    
  • Add event implementation and exception information analysis

      private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
      {
          string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
          // Subsequent processing, saving or output
      }
    
      private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
      {
          string str = GetExceptionMsg(e.Exception, e.ToString());
          // Subsequent processing, saving or output
      }
    
      static string GetExceptionMsg(Exception ex, string backStr)
      {
          StringBuilder sb = new StringBuilder();
          sb.AppendLine("****************************Abnormal text****************************");
          sb.AppendLine("[Time of occurrence]:" + DateTime.Now.ToString());
          if (ex != null)
          {
              sb.AppendLine("[Exception type]:" + ex.GetType().Name);
              sb.AppendLine("[Exception information]:" + ex.Message);
              sb.AppendLine("[Stack call]:" + ex.StackTrace);
    
              sb.AppendLine("[Abnormal method]:" + ex.TargetSite);
    
          }
          else
          {
              sb.AppendLine("[Unhandled exception]:" + backStr);
          }
          sb.AppendLine("***************************************************************");
          return sb.ToString();
      }
    

Posted by neron-fx on Thu, 05 Dec 2019 05:41:16 -0800