For a test on unhandled exception I created following simple .NET 5
project hoping that the global DispatcherUnhandledException Event would catch the error, but the error was raised locally and did not trigger the above event. Question: What I may be missing here, and how can we fix the issue. Maybe, a VS2019
debug setting or something else?
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
Error does NOT get caught here. According to this tutorial, as well, error should have been handled by this event, or else I may not be doing some thing right.
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;
}
}
Error occurs at line str.Trim() of btnTest_Click(...) event as follows: