Handling an unhandled exception
If a .NET exception goes unhandled, the process crashes with an unpleasant dialog presented to the user by Windows. Unpleasantness aside, the user may lose data as a result of the crash.
WPF provides a way to catch unhandled exceptions and perhaps handle them in some meaningful way. At the very least, the application may present a friendlier looking crash report and perhaps write the exception information to some log. At best, the application may recover from the error and continue running normally. Let's see how this can be done.
Getting ready
Make sure Visual Studio is up and running.
How to do it...
We'll create a simple application that throws an unhandled exception and see how we can catch it even if it's unhandled:
Create a new WPF Application project named
CH05.UnhandledExceptions
.Open
MainWindow.xaml
. Add aButton
to theGrid
as follows:<Button Content="Throw Exception" FontSize="20" Margin="10" />
Add a
Click
handler to the button. In the handler...