一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
/// <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(); } } } } |
比较简单,该类仅定义了一个属性和一个方法。具体使用如下:系统底层(例如数据访问层或业务逻辑层)发现异常时, 记录异常信息,将异常上抛。例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
//后台处理 try { //有可能发生异常操作 } catch (Exception ex) { string strSlq = "" ; ExceptionExtension.WriterExceptionLog(ex, "在查询记录时发生异常。SQL语句为:" + strSlq); throw ; //向上抛出异常 } finally { //清理 } |
用户交互层,捕获底层异常,显示提示信息。例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//用户界面 try { //调用底层有可能发生异常操作 } catch (Exception) { //MessageBox.Show(ExceptionExtension.ErrorMessage, "系统异常错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { //清理 } |
到此这篇关于C# WINFORM自定义异常处理方法的文章就介绍到这了,更多相关C# WINFORM异常处理方法内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://www.cnblogs.com/LiYunQi/archive/2021/12/31/15751493.html