WinForm C#全局错误捕捉处理【整理】
生活随笔
收集整理的這篇文章主要介紹了
WinForm C#全局错误捕捉处理【整理】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 static class Program
2 {
3 /// <summary>
4 /// 應用程序的主入口點。
5 /// </summary>
6 [STAThread]
7 static void Main()
8 {
9 try
10 {
11
12 //添加事件處理程序未捕獲的異常
13 Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
14 //添加事件處理UI線程異常
15 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
16 //添加事件處理非UI線程異常
17 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
18
19
20 Application.EnableVisualStyles();
21 Application.SetCompatibleTextRenderingDefault(false);
22 Application.Run(new FrmActivity());
23 }
24 catch (Exception ex)
25 {
26 string str = "";
27 string strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now.ToString() + "\r\n";
28
29 if (ex != null)
30 {
31 str = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n異常信息:{2}\r\n",
32 ex.GetType().Name, ex.Message, ex.StackTrace);
33 }
34 else
35 {
36 str = string.Format("應用程序線程錯誤:{0}", ex);
37 }
38
39 //寫日志
40 WriteLog.WriteErrLog(str);
41 MessageBox.Show("發生致命錯誤,請及時聯系作者!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
42 }
43
44 }
45
46 /// <summary>
47 ///這就是我們要在發生未處理異常時處理的方法,做法很多,可以是把出錯詳細信息記錄到文本、數據庫,發送出錯郵件到作者信箱或出錯后重新初始化等等
48 /// </summary>
49 /// <param name="sender"></param>
50 /// <param name="e"></param>
51 static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
52 {
53
54 string str = "";
55 string strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now.ToString() + "\r\n";
56 Exception error = e.Exception as Exception;
57 if (error != null)
58 {
59 str = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n異常信息:{2}\r\n",
60 error.GetType().Name, error.Message, error.StackTrace);
61 }
62 else
63 {
64 str = string.Format("應用程序線程錯誤:{0}", e);
65 }
66 //寫日志
67 WriteLog.WriteErrLog(str);
68 MessageBox.Show("發生致命錯誤,請及時聯系作者!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
69 }
70 /// <summary>
71 /// ' 處理UI異常
72 /// </summary>
73 /// <param name="sender"></param>
74 /// <param name="e"></param>
75 static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
76 {
77 string str = "";
78 Exception error = e.ExceptionObject as Exception;
79 string strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now.ToString() + "\r\n";
80 if (error != null)
81 {
82 str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆棧信息:{1}", error.Message, error.StackTrace);
83 }
84 else
85 {
86 str = string.Format("Application UnhandledError:{0}", e);
87 }
88 //寫日志
89 WriteLog.WriteErrLog(str);
90 MessageBox.Show("發生致命錯誤,請停止當前操作并及時聯系作者!", "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
91 }
92
93 }
?
轉載于:https://www.cnblogs.com/thirst/p/4153798.html
總結
以上是生活随笔為你收集整理的WinForm C#全局错误捕捉处理【整理】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Lync Server 2010 安装部
- 下一篇: c# char unsigned_dll