Click here to Skip to main content
15,861,168 members
Articles / Desktop Programming / WPF

Unhandled Exception Handler For WPF Applications

Rate me:
Please Sign up or sign in to vote.
4.85/5 (41 votes)
30 Jun 2010CPOL4 min read 143K   41   17
The article will demonstrate how you could handle Unhandled Exceptions from both UI and NonUI threads for your WPF application.

Introduction

Exception handling is very vital for any software. We use our traditional way of handling exceptions of our code using Try/ Catch / Finally block to handle runtime exceptions. We write our code inside a try block and wait for the error being generated from the code, and write our proper catch block to handle the Exception if generated while running the code. Compiler handles all these problems and calls the appropriate catch automatically. We write various Catch blocks which handle the exception based on the type of exception that occurs. After the exception is handled properly, the normal execution of the program remains unaffected.

Well, this is very normal for any program. Even though we always try to make our code Ultra-Defensive, sometimes we fall in a prank when our client tells us about an Weird Exception that took place in their environment. Maybe, you browse the whole solution to find the problem, and don't find the actual issue. Yes, there are lots of exceptions that you cannot handle from your code.

Exception on UI Thread (Dispatcher)

Say your client could not install your application properly and missed out a couple of DLLs or missed out themes that you might have used from your code. In these scenarios, we need to use a global handler which you want to be executed whenever any exception is not handled by your code, or exception which is generated in extreme cases. In case of WPF applications, Application.DispatcherUnhandledException comes in most handy in this situation.

WPF application object comes with DispatcherUnhandledException, an event which is generated automatically whenever application is going to be crashed after an exception is generated. Let us generate and see the code on how you could handle these situations:

XML
<Application x:Class="UnhandledExceptionHandler.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml"
    Startup="Application_Startup"
    DispatcherUnhandledException="Application_DispatcherUnhandledException">
    <Application.Resources>
         
    </Application.Resources>
</Application>

In the above code, you can see that I have added an EventHandler for the application. The DispatcherUnhandledException is called whenever the UI thread of the application generated an unhandled exception. To handle the exception, we write:

C#
public bool DoHandle { get; set; }
private void Application_DispatcherUnhandledException(object sender, 
                       System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
     if (this.DoHandle)
      {
          //Handling the exception within the UnhandledException handler.
          MessageBox.Show(e.Exception.Message, "Exception Caught", 
                                  MessageBoxButton.OK, MessageBoxImage.Error);
          e.Handled = true;
      }
      else
      {
          //If you do not set e.Handled to true, the application will close due to crash.
          MessageBox.Show("Application is going to close! ", "Uncaught Exception");
          e.Handled = false;
      }
 }

Importance of e.Handled

In the above code, I have placed a bool property to determine if we need to handle the exception or not. You can see, if the value of DoHandle is true, I have set e.Handled = true and vice-versa.

DispatcherUnhandledExceptionEventArgs comes with few arguments.

  1. Exception: This object is the actual Exception that is generated from the application.
  2. Dispatcher: You might already know, Dispatcher points to the UI thread.
  3. Handled: It determines if the block has already handled the exception. The default value for e.Handled = false, which means, the application still has the exception.

Thus in our case, if you do not put e.Handled = true, the application will eventually crash down. So it is very important to set the property e.Handled = true after you handle the exception.

Please note: Sometimes, even though you did set e.Handled = true, the application might crash. This depends on the severity of the Exception.

Exception on Custom Threads

In case of your custom Threads, your exception will not be caught by the DispatcherUnhandledException. This event hooks only the UI thread, and is only called when the UI thread gets an exception which crashes the program. If you need to handle the Exception occurring from a Non UI Thread, you can handle the UnhandledException that comes with AppDomain.

If you are not running your Threads in a new AppDomain, you might handle the UnhandledException event of AppDomain, and this would be called whenever any thread that runs on the AppDomain gets an Exception Object. To make it most simple, I have used AppDomain.CurrrentDomain.UnhandledException.

C#
private void Application_Startup(object sender, StartupEventArgs e)
{
     AppDomain.CurrentDomain.UnhandledException += 
                  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
}

void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
      Exception ex = e.ExceptionObject as Exception;
      MessageBox.Show(ex.Message, "Uncaught Thread Exception", 
                      MessageBoxButton.OK, MessageBoxImage.Error);
}

In the above code, you can see that I have handled the CurrentDomain.UnhandledException. This event will get executed whenever any UnhandledException occurs inside a NonUI Thread.

Sample Application

To demonstrate, I have provided a sample application. The application has a Button, which generates Exception, three RadioButton to demonstrate the exception on various scenario and one CheckBox to invoke the Exception from inside a Non-UI thread.

If you run the application, you will see that the first RadioButton gives you a MessageBox that it is handled within the block which generates the Exception. The second RadioButton will catch the Exception on DispatcherUnhandledException handler, and the third will crash the whole application.

You can download the source here.

I hope you like this post. Thank you all for reading.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.
http://bit.ly/EXPERTCookBook

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
BugShow message of Inner Exception if available Pin
George I. Birbilis26-Nov-15 13:42
George I. Birbilis26-Nov-15 13:42 
QuestionNice article. Pin
Gul Md Ershad30-Aug-14 20:19
Gul Md Ershad30-Aug-14 20:19 
QuestionWhy I don't get EF errors Pin
Chen Noam10-Aug-14 7:06
Chen Noam10-Aug-14 7:06 
QuestionWhat about task instances? Pin
korgy28-May-13 4:56
korgy28-May-13 4:56 
AnswerRe: What about task instances? Pin
JLRobinson15-Jan-14 4:52
JLRobinson15-Jan-14 4:52 
GeneralMy vote of 4 Pin
Vinoth Arun Raj. X9-Apr-13 2:35
Vinoth Arun Raj. X9-Apr-13 2:35 
QuestionHow to handle exception which was thrown in non-UI thread. Pin
sumus16-Jan-13 11:19
sumus16-Jan-13 11:19 
AnswerRe: How to handle exception which was thrown in non-UI thread. Pin
George I. Birbilis26-Nov-15 13:31
George I. Birbilis26-Nov-15 13:31 
QuestionStop the app from crashing Pin
dehpch3-Jan-12 5:00
dehpch3-Jan-12 5:00 
GeneralMy vote of 2 Pin
dehpch3-Jan-12 4:54
dehpch3-Jan-12 4:54 
GeneralMy vote of 5 Pin
PetrosPetrosean23-Jul-11 10:05
PetrosPetrosean23-Jul-11 10:05 
GeneralAppDomain.UnhandledException does not handle the exception Pin
petunyaf8418-Aug-10 7:50
petunyaf8418-Aug-10 7:50 
GeneralRe: AppDomain.UnhandledException does not handle the exception Pin
Abhishek Sur18-Aug-10 10:03
professionalAbhishek Sur18-Aug-10 10:03 
GeneralMy vote of 5 Pin
iDesmet9-Jul-10 18:46
iDesmet9-Jul-10 18:46 
GeneralRe: My vote of 5 Pin
Abhishek Sur18-Aug-10 10:03
professionalAbhishek Sur18-Aug-10 10:03 
GeneralMy vote of 5 Pin
Bogdan Marian6-Jul-10 1:03
professionalBogdan Marian6-Jul-10 1:03 
GeneralRe: My vote of 5 Pin
Abhishek Sur6-Jul-10 10:38
professionalAbhishek Sur6-Jul-10 10:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.