SoFunction
Updated on 2025-04-06

Catching when C# program is closed abnormally

This article mainly uses a simple small example to describe how to capture and record logs when the C# Winform program is closed abnormally.

Overview

Sometimes in the interface event, there is a try... catch to catch exceptions, but there will still be exceptions closed. Therefore, how to finally record some uncaught exceptions in the program will greatly facilitate the positioning analysis and program optimization of the problem.

Involved in knowledge points

The following two exception events are mainly used in different scenarios.

  • The event that occurs when a thread exception is not caught in the main thread of the application UI occurs.
  • Triggered when an exception in the background thread is not caught.

source code

Main Program:

using System;
using ;
using ;
using ;
using ;
using ;
using ;

namespace DemoException
{
  static class Program
  {
    /// <summary>
    /// The main entry point of the application.    /// </summary>
    [STAThread]
    static void Main()
    {
      ();
      // Handle UI thread exception       += new (Application_ThreadException);
      // Handle non-threaded exceptions       +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException) ;
      ();
      (false);
      (new FrmMain());
      glExitApp = true;//The flag application can exit    }

    /// <summary>
    /// Whether to exit the application    /// </summary>
    static bool glExitApp = false;

    /// <summary>
    /// Handle uncaught exceptions    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {

      SaveLog("-----------------------begin--------------------------");
      SaveLog("CurrentDomain_UnhandledException"+("yyyy-MM-dd hh:mm:ss"));
      SaveLog("IsTerminating : " + ());
      SaveLog(());
      SaveLog("-----------------------end----------------------------");
      while (true)
      {//Loop processing, otherwise the application will exit        if (glExitApp)
        {//The application can exit, otherwise the process is still running after the program exits          SaveLog("ExitApp");
          return;
        }
        (2 * 1000);
      };
    }

    /// <summary>
    /// Handle UI main thread exception    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void Application_ThreadException(object sender,  e)
    {
      SaveLog("-----------------------begin--------------------------");
      SaveLog("Application_ThreadException:" + );
      SaveLog();
      SaveLog("-----------------------end----------------------------");
    }

    public static void SaveLog(string log)
    {
      string filePath =+ @"\";
      //Use the using keyword and will be automatically released      using (FileStream fs = new FileStream(filePath, ))
      {
        using (StreamWriter sw = new StreamWriter(fs, ))
        {
          (log);
        }
      }
    }
  }
}

Error program:

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;

namespace DemoException
{
  public partial class FrmMain : Form
  {

    public FrmMain()
    {
      InitializeComponent();
    }

    private void FrmMain_Load(object sender, EventArgs e)
    {
      
    }

    private void btnTestUI_Click(object sender, EventArgs e)
    {
      int a = 0;
      int c = 10 / a;
    }

    private void btnTest2_Click(object sender, EventArgs e)
    {
      Thread t = new Thread(new ThreadStart(() =>
      {
        int a = 0;
        int c = 10 / a;
      }));
       = true;
      ();
    }
  }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.