C WinForm captures unhandled exception instance resolution

  • 2020-09-28 09:07:28
  • OfStack

This article presents a complete example of how C# WinForm catches unhandled exceptions. To share with you for your reference. The specific code is as follows:


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;
namespace GobalException
{
  static class Program
  {
    /// <summary>
    ///  The main entry point to the application. 
    /// </summary>
    [STAThread]
    static void Main()
    {
      try
      {
        // Handle uncaught exceptions   
        Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
        // To deal with UI Abnormal thread   
        Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
        // The non UI Abnormal thread   
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
      }
      catch (Exception ex)
      {
        string str = "";
        string strDateInfo = " An unhandled exception occurred in the application: " + DateTime.Now.ToString() + "\r\n";
        if (ex != null)
        {
          str = string.Format(strDateInfo + " Exception type: {0}\r\n Exception message: {1}\r\n Exception information: {2}\r\n",
             ex.GetType().Name, ex.Message, ex.StackTrace);
        }
        else
        {
          str = string.Format(" Application thread error :{0}", ex);
        }

        writeLog(str);
//frmBug f = new frmBug(str);// Friendly prompt interface 
      //f.ShowDialog();
        MessageBox.Show(" Fatal error, please contact the author in time! ", " System error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }
    /// <summary>
    /// So this is how we're going to handle an unhandled exception, and I'm going to write the error details into the text, like the error pops up 1 A beautiful error prompt form, for everyone to do a reference 
    /// There are many ways to do this, such as logging error details into text, databases, sending an error message to the author's mailbox, or reinitializing after an error, etc 
    /// It's a matter of opinion, you do it yourself. 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
      
      string str = "";
      string strDateInfo = " An unhandled exception occurred in the application: " + DateTime.Now.ToString() + "\r\n";
      Exception error = e.Exception as Exception;
      if (error != null)
      {
        str = string.Format(strDateInfo + " Exception type: {0}\r\n Exception message: {1}\r\n Exception information: {2}\r\n",
           error.GetType().Name, error.Message, error.StackTrace);
      }
      else
      {
        str = string.Format(" Application thread error :{0}", e);
      }
      writeLog(str);  
//frmBug f = new frmBug(str);// Friendly prompt interface 
      //f.ShowDialog();
      MessageBox.Show(" Fatal error, please contact the author in time! ", " System error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {
      string str = "";
      Exception error = e.ExceptionObject as Exception;
      string strDateInfo = " An unhandled exception occurred in the application: " + DateTime.Now.ToString() + "\r\n";
      if (error != null)
      {
        str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r The stack information :{1}", error.Message, error.StackTrace);
      }
      else
      {
        str = string.Format("Application UnhandledError:{0}", e);
      }
      writeLog(str);
//frmBug f = new frmBug(str);// Friendly prompt interface 
      //f.ShowDialog();
      MessageBox.Show(" Fatal error occurred, please stop the current operation and contact the author! ", " System error ", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    /// <summary>
    ///  Write files 
    /// </summary>
    /// <param name="str"></param>
    static void writeLog(string str)
    {
      if (!Directory.Exists("ErrLog"))
      {
        Directory.CreateDirectory("ErrLog");
      }
      using (StreamWriter sw = new StreamWriter(@"ErrLog\ErrLog.txt", true))
      {
        sw.WriteLine(str);
        sw.WriteLine("---------------------------------------------------------");
        sw.Close();
      }
    }
  }
}

The example of this article with more detailed notes, easy to read and understand. Hopefully this article has helped you with your C# programming.


Related articles: