C#程序異常關(guān)閉時(shí)的捕獲

本文主要以一個(gè)簡單的小例子,描述C# Winform程序異常關(guān)閉時(shí),如何進(jìn)行捕獲,并記錄日志。

我們提供的服務(wù)有:網(wǎng)站制作、成都網(wǎng)站設(shè)計(jì)、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、雨花ssl等。為上1000家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的雨花網(wǎng)站制作公司

概述

有時(shí)在界面的事件中,明明有try... catch 進(jìn)行捕獲異常,但是還是會有異常關(guān)閉的情況,所以在程序中如何最終的記錄一些無法捕獲的異常,會大大方便問題的定位分析及程序優(yōu)化。

涉及知識點(diǎn)

以下兩個(gè)異常事件,主要應(yīng)用不同的場景。

  • Application.ThreadException 在發(fā)生應(yīng)用程序UI主線程中未捕獲線程異常時(shí)發(fā)生,觸發(fā)的事件。
  • AppDomain.CurrentDomain.UnhandledException 當(dāng)后臺線程中某個(gè)異常未被捕獲時(shí)觸發(fā)。

源代碼

主要程序(Program):

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoException
{
  static class Program
  {
    /// <summary>
    /// 應(yīng)用程序的主入口點(diǎn)。
    /// </summary>
    [STAThread]
    static void Main()
    {
      Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
      //處理UI線程異常
      Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
      //處理非線程異常
      AppDomain.CurrentDomain.UnhandledException +=new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException) ;
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new FrmMain());
      glExitApp = true;//標(biāo)志應(yīng)用程序可以退出
    }

    /// <summary>
    /// 是否退出應(yīng)用程序
    /// </summary>
    static bool glExitApp = false;

    /// <summary>
    /// 處理未捕獲異常
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {

      SaveLog("-----------------------begin--------------------------");
      SaveLog("CurrentDomain_UnhandledException"+DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));
      SaveLog("IsTerminating : " + e.IsTerminating.ToString());
      SaveLog(e.ExceptionObject.ToString());
      SaveLog("-----------------------end----------------------------");
      while (true)
      {//循環(huán)處理,否則應(yīng)用程序?qū)顺?        if (glExitApp)
        {//標(biāo)志應(yīng)用程序可以退出,否則程序退出后,進(jìn)程仍然在運(yùn)行
          SaveLog("ExitApp");
          return;
        }
        System.Threading.Thread.Sleep(2 * 1000);
      };
    }

    /// <summary>
    /// 處理UI主線程異常
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
    {
      SaveLog("-----------------------begin--------------------------");
      SaveLog("Application_ThreadException:" + e.Exception.Message);
      SaveLog(e.Exception.StackTrace);
      SaveLog("-----------------------end----------------------------");
    }

    public static void SaveLog(string log)
    {
      string filePath =AppDomain.CurrentDomain.BaseDirectory+ @"\objPerson.txt";
      //采用using關(guān)鍵字,會自動釋放
      using (FileStream fs = new FileStream(filePath, FileMode.Append))
      {
        using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
        {
          sw.WriteLine(log);
        }
      }
    }
  }
}

出錯(cuò)的程序:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

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;
      }));
      t.IsBackground = true;
      t.Start();
    }
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

當(dāng)前標(biāo)題:C#程序異常關(guān)閉時(shí)的捕獲
網(wǎng)頁網(wǎng)址:http://bm7419.com/article26/igcjjg.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、全網(wǎng)營銷推廣、網(wǎng)站制作網(wǎng)站策劃、ChatGPT、網(wǎng)站收錄

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)