处理异常后发生未处理的异常

DIl*_*d K 1 c# wpf unhandled-exception

我的preveus问题中的这个主题:如何在Windows事件查看器中删除和创建日志

我创建了wpf app.我用3种方式捕捉未处理的异常:

public partial class App : Application
{
    public App()
    {
        DispatcherUnhandledException += App_DispatcherUnhandledException;
        Dispatcher.UnhandledException += Dispatcher_UnhandledException;
        AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
    }

    private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
    {

    }

    private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {

    }

    private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
    {

    }
}
Run Code Online (Sandbox Code Playgroud)

我正在创建这样的异常:

   public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        throw new Exception("Test exception");
    }
}
Run Code Online (Sandbox Code Playgroud)

在执行方法(Dispatcher_UnhandledException,)之后CurrentDomain_UnhandledException,App_DispatcherUnhandledException这个异常仍在抛出.Windows事件查看器正在创建这样的日志

描述:由于未处理的异常,进程终止.异常信息:System.Data.ProviderBase.DbConnectionFactory.TryGetConnection的System.InvalidOperationException(System.Data.Common.DbConnection,System.Threading.Tasks.TaskCompletionSource 1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions, System.Data.ProviderBase.DbConnectionInternal, System.Data.ProviderBase.DbConnectionInternal ByRef) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource1

Gab*_*uci 6

在处理程序方法中,您需要告诉.NET您处理了异常.否则它仍会杀死该应用程序.您可以使用对象的Handled属性执行此操作DispatcherUnhandledExceptionEventArgs.

因此,如果您决定在异常情况下继续应用程序,请将其设置为true:

private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    e.Handled = true; //let's continue and see if anything explodes
}
Run Code Online (Sandbox Code Playgroud)

也就是说,您应该仍然可以处理可能发生的异常(尽可能多).以您给出的示例为例,这看起来像是网络连接问题.如果您在创建连接时遇到该异常,则可以告诉用户更具体的内容,例如"我无法连接到数据库.您的网络是否正常工作?" 然而,如果你依靠这个来捕获这种错误,那么你只能反驳异常消息,这通常对用户没有意义.

这应该用作最后的故障保护.它不应该取代整个代码中的捕获异常.