C#中全局处理异常方式
生活随笔
收集整理的這篇文章主要介紹了
C#中全局处理异常方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
using System;
using System.Configuration;
using System.Text;
using System.Windows.Forms;
using ZB.QueueSys.Common;namespace ZB.QueueSys
{static class Program{/// <summary>/// 應用程序的主入口點。/// </summary>[STAThread]static void Main(){Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);//處理UI線程異常 Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);//處理非UI線程異常 AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);//數據庫類型DBHelper.Instance.DBType = int.Parse(ConfigurationManager.AppSettings["DBType"]);//數據庫連接串DBHelper.Instance.ConnectionStr = ConfigurationManager.ConnectionStrings["DBStr"].ConnectionString;Application.Run(new MainForm());//Application.Run(new QueueForm());}private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e){string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());LogHelper.Instance.SaveText(str);Exception error = e.ExceptionObject as Exception;MessageBox.Show(error.Message, "系統異常提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);}private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e){string str = GetExceptionMsg(e.Exception, e.ToString());LogHelper.Instance.SaveText(str);MessageBox.Show(e.Exception.Message, "系統異常提示信息", MessageBoxButtons.OK, MessageBoxIcon.Error);}/// <summary> /// 生成自定義異常消息 /// </summary> /// <param name="ex">異常對象</param> /// <param name="backStr">備用異常消息:當ex為null時有效</param> /// <returns>異常字符串文本</returns> private static string GetExceptionMsg(Exception ex, string backStr){StringBuilder sb = new StringBuilder();sb.AppendLine("****************************異常文本****************************");sb.AppendLine("【出現時間】:" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"));if (ex != null){sb.AppendLine("【異常類型】:" + ex.GetType().Name);sb.AppendLine("【異常信息】:" + ex.Message);sb.AppendLine("【堆棧調用】:" + ex.StackTrace);sb.AppendLine("【異常方法】:" + ex.TargetSite);}else{sb.AppendLine("【未處理異常】:" + backStr);}sb.AppendLine("***************************************************************");return sb.ToString();}}
}
轉載于:https://www.cnblogs.com/YYkun/p/8952924.html
總結
以上是生活随笔為你收集整理的C#中全局处理异常方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 爱情公寓5什么时候上映 鹿晗刘诗诗加盟爱
- 下一篇: 广州环滘村滴滴搭车过去广州流花车站大概多