以下操作在Program.cs中
1.最簡單的方式try...catch..
一般用在某一段容易出錯的代碼,如果用在整個軟件排查,如下所示
static void Main()
{
try
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
catch (Exception ex)
{
MessageBox.Show(string.Format("捕獲到未處理的異常:{0}\n異常信息:{1}\n異常堆棧:{2}", ex.GetType(), ex.Message, ex.StackTrace));
}
}
2.上面的方法並不是很好的方式,下面這種更好一些。
主線程事件監聽:Application.ThreadException,程序並不會因為異常而退出。
子線程異常捕獲AppDomain.CurrentDomain.UnhandledException
static void Main()
{
Application.ThreadException += Application_ThreadException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FrmMain());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = e.ExceptionObject as Exception;
MessageBox.Show(string.Format("捕獲到未處理異常:{0}\n異常信息:{1}\n異常堆棧:{2}\r\nCLR即將退出:{3}", ex.GetType(), ex.Message, ex.StackTrace, e.IsTerminating));
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
Exception ex = e.Exception;
MessageBox.Show(string.Format("捕獲到未處理異常:{0}\n異常信息:{1}\n異常堆棧:{2}", ex.GetType(), ex.Message, ex.StackTrace));
}