WPF:處理常式的“未處理異常”

來源:互聯網
上載者:User

我首先想到的是應用程式定義域AppDomain類型的UnhandledExceptionEventHandler,試了試才知道原來AppDomain.UnhandledExceptionEventHandler就是一個通知性質的事件,沒有處理異常的功能,自然未處理異常還會是程式崩潰。它的UnhandledExceptionEventArgs中有兩個屬性:IsTerminating和ExceptionObject,分別代表程式是否在崩潰和引起崩潰的異常對象。

 

比如這段代碼:

static void Main(string[] args)

{

    AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

    throw new Exception("test");

}

 

static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)

{

    Console.WriteLine("完蛋了?:" + e.IsTerminating);

    Console.WriteLine("誰乾的?:" + e.ExceptionObject);

}

 

結果:

程式還是崩潰了……

看來.NET Framework BCL中沒有專門處理CLR未處理異常的方法。

 

看來WPF程式只能使用自己的Dispatcher.UnhandledException事件,這個事件碉堡了,任何當前Dispatcher線程(即UI線程)的未處理異常都可以選擇處理或者不處理(通過DispatcherUnhandledExceptionEventArgs.IsHandled屬性),選擇處理的話未處理異常就不會崩潰整個WPF應用程式了。

 

比如在按鈕點擊後拋出一個異常:

private void Button_Click(object sender, RoutedEventArgs e)

{

    Dispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException);

    throw new Exception("test");

}

 

void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)

{

    MessageBox.Show(e.Exception.Message, "錯誤", MessageBoxButton.OK, MessageBoxImage.Error);

    e.Handled = true;

}

 

結果:

一個訊息框出現,關閉後程式繼續運行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.