代码之家  ›  专栏  ›  技术社区  ›  nam

WPF。NET 5简单错误未被DispatcherUnhandledException事件捕获[重复]

  •  0
  • nam  · 技术社区  · 3 年前

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

    主窗口.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>
    

    主窗口.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>
    

    代码文件

    此处未发现错误。根据 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;
        }
    }
    

    第行出现错误 btnTest_Click(…)事件的str.Trim(),如下所示:

    enter image description here

    1 回复  |  直到 3 年前
        1
  •  -1
  •   LarryX    3 年前

    是,在调试模式下,“异常”对话框将首先捕获异常。如果您点击continue几次,它将弹出并被Application_DispatcherUnhandledException捕获。

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