本文轉載自:http://www.cnblogs.com/yinzixin/
非常有用的文章, 感謝yinzixin
-----------------------------------
如果Windows Forms程式中有未被捕獲的異常,會導致程式崩潰並且給使用者造成不良的印象。例如下面的程式,類比了一個未捕獲的異常:
按鈕事件為:
private void button1_Click(object sender, EventArgs e)
{
throw new Exception();
}
點擊Exception 按鈕,會彈出如下預設視窗
Windows Forms提供了兩個事件來處理未捕獲的異常發生時的情況,分別是 Application.ThreadException和AppDomain.UnhandledException事件,前者用來處理UI線程中的異 常,後者處理其他線程中的異常。要使程式使用自訂的事件來處理異常,可以使用如下代碼:
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
MessageBox.Show("抱歉,您的操作沒有能夠完成,請再試一次或者聯絡軟體供應商");
LogUnhandledException(e.ExceptionObject);
}
static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
MessageBox.Show("抱歉,您的操作沒有能夠完成,請再試一次或者聯絡軟體供應商");
LogUnhandledException(e.Exception);
}
static void LogUnhandledException(object exceptionobj)
{
//Log the exception here or report it to developer
}
}
此時運行該程式的結果如下: