这篇文章主要介绍了一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。需要的可以参考一下
一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。
/// <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
{
//清理
}
到此这篇关于C# WINFORM自定义异常处理方法的文章就介绍到这了,更多相关C# WINFORM异常处理方法内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
织梦狗教程
本文标题为:C# WINFORM自定义异常处理方法


基础教程推荐
猜你喜欢
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#中的Linq to JSON操作详解 2023-06-08
- C# 解析XML和反序列化的示例 2023-04-14
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity shader实现高斯模糊效果 2023-01-16
- Unity 如何获取鼠标停留位置下的物体 2023-04-10
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- 实例详解C#实现http不同方法的请求 2022-12-26