我們在開發winform程序的時候經常需要處理異常,如果沒處理好異常程序就會崩潰,影響用戶體驗。
所以防止程序在沒處理到異常時能由一個全局的異常捕獲處理,在winform的program文件里面我們可以添加全局異常捕獲事件,然后處理異常。
在program的main方法里面設置異常處理方式,然后注冊異常處理的兩個事件:
1.設置異常處理方式
//處理未捕獲的異常
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
2.ThreadException 處理UI線程異常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application_ThreadException方法:
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string str = "";
string strDateInfo = "\r\n\r\n出現應用程序未處理的異常:" + DateTime.Now.ToString() + "\r\n";
Exception error = e.Exception as Exception;
if (error != null)
{
string logInfo = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n異常信息:{2}\r\n", error.GetType().Name, error.Message, error.StackTrace);
str = string.Format(strDateInfo + "異常類型:{0}\r\n異常消息:{1}\r\n",
error.GetType().Name, error.Message);
}
else
{
str = string.Format("應用程序線程錯誤:{0}", e);
}
MessageBox.Show(str, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
3.UnhandledException 處理非UI線程異常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
CurrentDomain_UnhandledException 方法:
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = "";
Exception error = e.ExceptionObject as Exception;
string strDateInfo = "出現應用程序未處理的異常:" + DateTime.Now.ToString() + "\r\n";
if (error != null)
{
string logInfo = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r堆棧信息:{1}", error.Message, error.StackTrace);
str = string.Format(strDateInfo + "Application UnhandledException:{0};\n\r", error.Message);
}
else
{
str = string.Format("Application UnhandledError:{0}", e);
}
MessageBox.Show(str, "系統錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
}