为了测试未处理的异常,我创建了以下简单的
.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();
}
}
}
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(),如下所示: