C# WINFORM异常处理方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C# WINFORM异常处理方法

李运琪   2022-05-23 我要评论

一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。 

 /// <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
 {
     //清理
 }

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们