Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Windows Presentation Foundation Development Cookbook

You're reading from   Windows Presentation Foundation Development Cookbook 100 recipes to build rich desktop client applications on Windows

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher Packt
ISBN-13 9781788399807
Length 524 pages
Edition 1st Edition
Arrow right icon
Author (1):
Arrow left icon
Kunal Chowdhury Kunal Chowdhury
Author Profile Icon Kunal Chowdhury
Kunal Chowdhury
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
1. WPF Fundamentals FREE CHAPTER 2. Using WPF Standard Controls 3. Layouts and Panels 4. Working with Data Bindings 5. Using Custom Controls and User Controls 6. Using Styles, Templates, and Triggers 7. Using Resources and MVVM Patterns 8. Working with Animations 9. Using WCF Services 10. Debugging and Threading 11. Interoperability with Win32 and WinForm 1. Other Books You May Enjoy Index

Handling unhandled exceptions


Exception handling is a vital part of software development. When an exception occurs at runtime, due to any error in the code, we handle those with a try {} catch {} block. The try {} block contains the code where the exception occurred; the catch {} block knows how to handle that, based on the type of the exception. After the exception has been handled, the normal execution of the program continues without affecting the application.

Though, in most of the cases we handle, there could be cases that may go unnoticed and come into the picture at runtime. Such an unhandled exception crashes the application. In this recipe, we will learn how to catch the unhandled exceptions in the WPF application and close the application properly.

Getting ready

To get started, open the Visual Studio IDE. Now create a new project, based on the WPF Application template, and call it CH01.UnhandledExceptionDemo.

How to do it...

Let's start the demonstration by following these steps:

  1. Open the MainWindow.xaml page, and add two radio buttons and one button on it. The first radio button will cause an exception handled in a try {} catch {} block, whereas the second radio button will throw an exception that will go unhandled. Add the following code into your MainWindow.xaml:
<Window x:Class="CH01.UnhandledExceptionDemo.MainWindow" 
  xmlns=
    "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="UnhandledException Demo"  
     Height="120" Width="400"> 
    <Grid Margin="10"> 
        <StackPanel Orientation="Vertical"> 
            <RadioButton x:Name="radioOne" GroupName="type" 
                  Content="Handle in Try/Catch Block"  
                  IsChecked="True" Margin="4"/> 
            <RadioButton x:Name="radioTwo" GroupName="type" 
                  Content="Handle in Unhandled Block"  
                  IsChecked="False" Margin="4"/> 
        </StackPanel> 
        <Button Content="Throw Exception"  
                Width="120" Height="30" 
                VerticalAlignment="Top"  
                HorizontalAlignment="Right" 
                Margin="10"  
                Click="OnThrowExceptionClicked"/> 
    </Grid> 
</Window> 
  1. Open the MainWindow.xaml.cs file to add the button-click event handler. Add the following code block inside the class:
private void OnThrowExceptionClicked(object sender, RoutedEventArgs e) 
{ 
    if (radioOne.IsChecked == true) 
    { 
        try { throw new Exception("Demo Exception"); } 
        catch (Exception ex) 
        { 
            MessageBox.Show("'" + ex.Message +  
                  "' handled in Try/Catch block"); 
        } 
    } 
    else 
    { 
        throw new Exception("Demo Exception"); 
    } 
} 
  1. Go to the App.xaml.cs file and override the OnStartup method to have the application level DispatcherUnhandledException event registered as shown in the following code:
protected override void OnStartup(StartupEventArgs e) 
{ 
    base.OnStartup(e); 
 
    DispatcherUnhandledException += OnUnhandledException; 
}
  1. Add the DispatcherUnhandledException event handler into the App.xaml.cs and handle the exception as shown in the following code, but with an empty code block:
private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 
{ 
 
} 
  1. Let's build and run the application. You will see the following UI on the screen:
  2. It will have two radio selectors and one button in the application window. When the first radio button is checked and you click on the Throw Exception button, it will generate an exception in a try {} block, which will then immediately be handled by the associated catch {} block without crashing the application. The following message box will be shown on the UI:
  1. For the second radio button, when checked, if you click on the Throw Exception button, the exception will go unhandled and will be caught in the App.xaml.cs file, under the OnUnhandledException event, and the application will crash:
  1. Open the App.xaml.cs once again and modify the OnUnhandledException event implementation, as follows, to handle the thrown exception:
private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) 
{ 
    e.Handled = true; 
} 
  1. Now run the application once again, check the second radio button and click on the button. You will notice that the application will not crash this time.
  2. Click the Throw Exception button multiple times. The application will continue as-is, without causing any crash of the UI.

How it works...

When you handle this kind of uncaught/unhandled exception by specifying e.Handled = true, your application will not crash and will continue running. The best part of catching an unhandled exception is logging the unknown/unhandled errors, so that you can investigate the root cause behind these exceptions and fix them in future builds.

When there's a critical error, you can restart the application programmatically from this block.

There's more...

You can also use the AppDomain.CurrentDomain.UnhandledException event handler to catch any unhandled exceptions, but you won't be able to handle it in a way to continue running the application. When used, you can log the error and terminate/restart the application.

Note

Unhandled exceptions handled in the DispatcherUnhandledException event, by specifying e.Handled = true will not route to the AppDomain.CurrentDomain.UnhandledException.

You have been reading a chapter from
Windows Presentation Foundation Development Cookbook
Published in: Feb 2018
Publisher: Packt
ISBN-13: 9781788399807
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images