WPF .NET 5 简单错误没有被 DispatcherUnhandledException 事件捕获

问题描述

为了测试未处理的异常,我创建了以下简单的 .NET 5 项目,希望全局 DispatcherUnhandledException 事件能够捕获错误,但该错误是在本地引发的,并没有触发上述事件。 问题:我在这里可能遗漏了什么,我们如何解决这个问题。也许,VS2019 调试设置或其他什么?

MainWindow.xaml

<Window x:Class="Wpf_DeleteJuly21.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wpf_DeleteJuly21"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <Button x:Name="btnTest" Content="Test" Width="26" Click="btnTest_Click"/>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

namespace Wpf_DeleteJuly21
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender,RoutedEventArgs e)
        {
            string str = null;
            str.Trim(); //error would occur here.
        }
    }
}

App.xaml

<Application x:Class="Wpf_DeleteJuly21.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Wpf_DeleteJuly21"
             StartupUri="MainWindow.xaml" dispatcherUnhandledException="Application_dispatcherUnhandledException">
    <Application.Resources>
         
    </Application.Resources>
</Application>

App.xaml.cs

此处不会捕获错误。根据 this 教程,错误也应该由这个事件处理,否则我可能做错了一些事情。

public partial class App : Application
{
    private void Application_dispatcherUnhandledException(object sender,System.Windows.Threading.dispatcherUnhandledExceptionEventArgs e)
    {
        MessageBox.Show("An unhandled exception occurred: " + e.Exception.Message,"Global Exception Test",MessageBoxButton.OK,MessageBoxImage.Warning);
        e.Handled = true;
    }
}

错误发生在行 str.Trim() of btnTest_Click(...) 事件如下:

enter image description here

解决方法

在调试模式下是,异常对话框将首先捕获异常。如果你多次点击 continue,它会冒泡并被 Application_DispatcherUnhandledException 捕获。

或者您可以尝试在不调试的情况下运行。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...