C# 處理unhandled Exception方式以下:
1. 在程序的Main()方法中增長以下代碼。
//處理線程未處理的異常
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
//處理系統未處理的異常
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
//運行程序
Application.Run(new frmServerMain());
2. 方法:
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
string str = "";
Exception error = e.Exception as Exception;
if (error != null)
{
str = string.Format("Application unhandled exception.\nExceptionType:{0}\nException Message: {1}\n StackTrace:{2}\n",
error.GetType().Name, error.Message, error.StackTrace);
}
else
{
str = string.Format("Application Thread Exception Msg:{0}", e);
}
WriteErrInfo(str);
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
string str = "";
Exception error = e.ExceptionObject as Exception;
if (error != null)
{
str = string.Format("Application UnhandledException:{0};\nStackTrace:{1}", error.Message, error.StackTrace);
}
else
{
str = string.Format("Application UnhandledError:{0}", e);
}
WriteErrInfo(str);
}
static void WriteErrInfo(string vErrMsg)
{
using (System.IO.FileStream fs = new System.IO.FileStream(Application.StartupPath + "\\Log\\TestException.log",
System.IO.FileMode.Append, System.IO.FileAccess.Write))
{
using (System.IO.StreamWriter w = new System.IO.StreamWriter(fs,System.Text.Encoding.UTF8))
{
w.WriteLine(vErrMsg); DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
}
}
}html
詳細分析可參見:線程
http://www.cnblogs.com/eaglet/archive/2009/02/17/1392191.htmlorm