如何處理Windows Forms程式中未處理的異常

來源:互聯網
上載者:User

本文轉載自: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
}
}

此時運行該程式的結果如下:

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.