日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#?WINFORM自定義異常處理方法_C#教程

作者:李運琪 ? 更新時間: 2022-03-21 編程語言

一個簡單的統一異常處理方法。系統底層出現異常,寫入記錄文件,系統頂層捕獲底層異常,顯示提示信息。?

 /// <summary>
    /// 自定義異常類
    /// </summary>
    public static class ExceptionExtension
 
    {
        /// <summary>
        /// 用戶自定義錯誤消息
        /// </summary>
        public static string ErrorMessage { get; set; }
 
        /// <summary>
        /// 寫入異常日志
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="Message">用戶自定義錯誤消息</param>
        public static void WriterExceptionLog(Exception ex, string Message = "")
        {
            string filePath = Environment.CurrentDirectory.Replace(@"\bin\Debug", "") + @"\ErrorLog";
            if (!System.IO.Directory.Exists(filePath))
            {
                System.IO.Directory.CreateDirectory(filePath);
            }
            string fileName = filePath + @"\ErrorLog.txt";
 
            StringBuilder errorInfo = new StringBuilder();
            errorInfo.Append($"*******異常發生時間:{DateTime.Now}*******\n");
            errorInfo.AppendFormat(" 異常類型: {0} \n", ex.HResult);
            //msg.AppendFormat(" 導致當前異常的 Exception 實例: {0} \n", ex.InnerException);
            errorInfo.AppendFormat(" 導致異常的應用程序或對象的名稱: {0} \n", ex.Source);
            errorInfo.AppendFormat(" 引發異常的方法: {0} \n", ex.TargetSite);
            errorInfo.AppendFormat(" 異常堆棧信息: {0} \n", ex.StackTrace);
            errorInfo.AppendFormat(" 異常消息: {0} \n", ex.Message);
            errorInfo.AppendFormat(" 系統信息: {0} \n", Message);
            ErrorMessage += Message;
            try
            {
                if (File.Exists(fileName))
                {
                    using (StreamWriter tw = File.AppendText(fileName))
                    {
                        tw.WriteLine(errorInfo.ToString());
                    }
                }
                else
                {
                    TextWriter tw = new StreamWriter(fileName);
                    tw.WriteLine(errorInfo.ToString());
                    tw.Flush();//將緩沖區的數據強制輸出,清空緩沖區
                    tw.Close();//關閉數據流
                    tw = null;
                }
            }
            catch (Exception) { Console.ReadKey(); }
        }
    }
}

比較簡單,該類僅定義了一個屬性和一個方法。具體使用如下:系統底層(例如數據訪問層或業務邏輯層)發現異常時, 記錄異常信息,將異常上拋。例如:

//后臺處理
try
{
    //有可能發生異常操作
}
catch (Exception ex)
{
    string strSlq = "";
    ExceptionExtension.WriterExceptionLog(ex, "在查詢記錄時發生異常。SQL語句為:" + strSlq);
    throw;//向上拋出異常
}
finally
{
    //清理
}

用戶交互層,捕獲底層異常,顯示提示信息。例如:

//用戶界面
 try
 {
     //調用底層有可能發生異常操作
 }
 catch (Exception)
 {
     //MessageBox.Show(ExceptionExtension.ErrorMessage, "系統異常錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
 }
 finally
 {
     //清理
 }

原文鏈接:https://www.cnblogs.com/LiYunQi/archive/2021/12/31/15751493.html

欄目分類
最近更新