How To Handle "WPF Application Has Stopped Working"

Our Application might have encountered some unhandled exceptions. In some cases, we implement try catch block to handle this but some are beyond our expectations and cause termination of the Application in WPF, as shown below.
In classic Windows form Application, if we caught any unhandled exception,  a dialog appears on the screen with the detailed exception message, which allows the user to continue using the Application or quit it, as shown below.
Thus, to avoid termination of WPF Application, we have to add some events in our Application by following the steps given below.
Step 1 

Open App.xaml.cs (under App.xaml) file from the Solution Explorer.
Step 2

Override the OnStartup method and add some events. 
  1. protected override void OnStartup(StartupEventArgs e)  
  3.            Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Current_DispatcherUnhandledException);  
  4.            DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);  
  5.            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);  
Step 3

Write the body part of the event. 
  1. void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)  
  2. {  
  3.         e.Handled = true;  
  4. }  
  6. void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)  
  7. {  
  8.        e.Handled = true;  
  9. }  
  11. void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)  
  12. {  
  13.         // we cannot handle this, but not to worry, I have not encountered this exception yet.  
  14.         // However, you can show/log the exception message and show a message that if the application is terminating or not.  
  15.         var isTerminating = e.IsTerminating;  
  16. }  

By writing these events for our Application, we can avoid WPF Application to terminate suddenly.
I hope, this will help many beginners to tackle an unhandled exception and avoid the termination of the Application.
Thank you for reading this blog. Stay connected with C# Corner for more updates. 

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now