WPF
global exception handler
duplicate
error handling
.NET

WPF global exception handler

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Windows Presentation Foundation (WPF) is a powerful UI framework for creating rich desktop applications on Windows. However, as with any software, exceptions can occur during runtime, potentially leading to application crashes. Implementing a global exception handler is an essential technique to manage unexpected exceptions gracefully, ensuring stability and providing a better user experience.

Understanding Exceptions in WPF

In the context of WPF applications, exceptions can occur in various parts of the application, from the application startup to UI logic, and data-binding operations. Exceptions may arise due to reasons like invalid input, null references, or unexpected results from asynchronous operations.

Types of Exceptions

  1. Synchronous Exceptions: These typically occur on the main UI thread and can be caught using try-catch blocks.
  2. Asynchronous Exceptions: These occur in tasks or asynchronous methods and need to be handled using specific mechanisms.
  3. UnhandledExceptions: An unhandled exception occurs when a try-catch block does not explicitly catch an exception, potentially leading to application termination.

Implementing a Global Exception Handler

To improve resilience, WPF provides several ways to set up a global exception handler. The two primary methods are handled via the AppDomain and the Application class.

Using AppDomain for Unhandled Exceptions

The AppDomain.UnhandledException event can catch exceptions that aren't caught within try-catch blocks on the main application domain. Here's how you can implement it:

csharp
1AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
2{
3    Exception ex = (Exception)e.ExceptionObject;
4    // Log the exception details
5    LogException(ex);
6    // Inform the user
7    MessageBox.Show("An unexpected error occurred: " + ex.Message);
8};

Using Application for DispatcherUnhandledException

For UI-related exceptions not handled within the application, WPF exposes the Application.DispatcherUnhandledException event:

csharp
1protected override void OnStartup(StartupEventArgs e)
2{
3    base.OnStartup(e);
4    this.DispatcherUnhandledException += OnDispatcherUnhandledException;
5}
6
7private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
8{
9    // Log the exception
10    LogException(e.Exception);
11    // Prevent the application from crashing
12    e.Handled = true;
13    // Notify user
14    MessageBox.Show("An error occurred: " + e.Exception.Message);
15}

Handling Task-Based Asynchronous Exceptions

For exceptions arising from async and await patterns, you can use task continuation options to catch exceptions:

csharp
1Task.Run(() =>
2{
3    // Some asynchronous work
4})
5.ContinueWith(task =>
6{
7    if (task.IsFaulted)
8    {
9        // Log and handle the exception
10        LogException(task.Exception);
11    }
12}, TaskContinuationOptions.OnlyOnFaulted);

Benefits of a Global Exception Handler

Having a global exception handler offers several advantages:

  • Stability: Prevents the application from terminating unexpectedly.
  • User Experience: Offers a way to inform users, improving their experience by providing meaningful error messages.
  • Debugging and Logging: Enables centralized exception logging, assisting in debugging and maintenance.

Best Practices

  1. Logging: Always log the exception details for further analysis. Use tools like NLog or Log4Net.
  2. User Feedback: Display user-friendly messages without technical jargon.
  3. Rethrow When Necessary: Consider rethrowing the exception after logging if it needs to be processed or escalated.
  4. Continuation Strategies: Define strategies for retrying or failing gracefully based on the exception type and severity.

Summary Table

Exception Handling TechniqueDescription
AppDomain.UnhandledExceptionCatches exceptions in the application domain; useful for non-UI exceptions.
Application.DispatcherUnhandledExceptionHandles exceptions for the UI thread; prevents crashes due to UI faults.
Task ContinuationsManages exceptions in asynchronous tasks with ContinueWith for faulted state handling.

Conclusion

Implementing a global exception handler is critical for developing robust WPF applications. By effectively handling exceptions at a central point, developers can improve application resilience, provide informative feedback to users, and ensure better maintenance and debugging practices. Properly managing exceptions not only enhances the user experience but also ensures the application's reliability and quality.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.