C# Winform 自定义异常处理方法
一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。
////// 自定义异常类 /// public static class ExceptionExtension { ////// 用户自定义错误消息 /// public static string ErrorMessage { get; set; } ////// 写入异常日志 /// /// /// 用户自定义错误消息 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
{
//清理
}
完成。