Application.DispatcherUnhandledException 事件

定義

當應用程式擲回例外狀況但未處理時發生。

public:
 event System::Windows::Threading::DispatcherUnhandledExceptionEventHandler ^ DispatcherUnhandledException;
public event System.Windows.Threading.DispatcherUnhandledExceptionEventHandler DispatcherUnhandledException;
member this.DispatcherUnhandledException : System.Windows.Threading.DispatcherUnhandledExceptionEventHandler 
Public Custom Event DispatcherUnhandledException As DispatcherUnhandledExceptionEventHandler 

事件類型

範例

下列範例示範如何藉由處理 DispatcherUnhandledException 事件來處理未處理的例外狀況。

using System.Windows;
using System.Windows.Threading;

namespace SDKSample
{
    public partial class App : Application
    {
        void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            // Process unhandled exception

            // Prevent default unhandled exception processing
            e.Handled = true;
        }
    }
}
Imports System.Windows
Imports System.Windows.Threading

Namespace SDKSample
    Partial Public Class App
        Inherits Application
        Private Sub App_DispatcherUnhandledException(ByVal sender As Object, ByVal e As DispatcherUnhandledExceptionEventArgs)
            ' Process unhandled exception

            ' Prevent default unhandled exception processing
            e.Handled = True
        End Sub
    End Class
End Namespace

備註

根據預設,Windows Presentation Foundation擷取未處理的例外狀況、通知使用者從對話方塊 (可以報告例外狀況) ,並自動關閉應用程式。

不過,如果應用程式需要從集中式位置執行自訂未處理的例外狀況處理,您應該處理 DispatcherUnhandledException

DispatcherUnhandledException 會針對 Application 在主要 UI 執行緒上執行的程式碼未處理的每個例外狀況引發 。

如果未在背景 UI 執行緒上處理例外狀況, (執行緒具有自己的 Dispatcher) 或背景背景背景工作執行緒 (沒有 Dispatcher) ,則例外狀況不會轉送到主要 UI 執行緒。 因此, DispatcherUnhandledException 不會引發 。 在這些情況下,您必須撰寫程式碼來執行下列動作:

  1. 處理背景執行緒上的例外狀況。

  2. 將這些例外狀況分派至主要 UI 執行緒。

  3. 在主要 UI 執行緒上重新擲回它們,而不需處理它們以允許 DispatcherUnhandledException 引發。

如需詳細資訊,請參閱 執行緒模型概 觀。

DispatcherUnhandledException事件處理常式會傳遞自 DispatcherUnhandledExceptionEventArgs 變數,其中包含有關例外狀況的內容資訊,包括:

您可以使用這項資訊來判斷例外狀況是否可復原。 可復原的例外狀況可能是 FileNotFoundException ,例如,而無法復原的例外狀況可能是 StackOverflowException ,例如。

當您處理 的 DispatcherUnhandledException 未處理例外狀況,而且您不想讓 WPF 繼續處理時,您必須將 Handled 屬性設定為 true

不同于引發的其他事件 ApplicationDispatcherUnhandledException 在 OnDispatcherUnhandledException) 沒有相符的受保護虛擬 (實作。 因此,衍生自 Application 的類別必須一律向 註冊事件處理常式 DispatcherUnhandledException ,以處理未處理的例外狀況。

適用於