-2

I have a WPF C# Application and I have included try catch in all the procedures, functions, event handlers, etc. But my application crashes and restarts at some point.

When application crashes, it shows a message that "This Application stops working....and restarts" with a ok button.

How we can handle it ?

sherin
  • 5
  • 4
  • 1
    Possible duplicate of [WPF global exception handler](https://stackoverflow.com/questions/1472498/wpf-global-exception-handler) – 15ee8f99-57ff-4f92-890c-b56153 Oct 23 '19 at 16:48
  • 1
    You might also want to check the event log on the machine it crashes on, this should give you some info about the crash and depending on your build may also give you a call stack. – Charleh Oct 23 '19 at 17:08
  • 1
    Possible duplicate of [Globally catch exceptions in a WPF application?](https://stackoverflow.com/questions/793100/globally-catch-exceptions-in-a-wpf-application) – Keith Stein Oct 23 '19 at 19:07

1 Answers1

-1

For the unhandled exception of UI thread, we use the application.dispatcherunhandledexception event to handle it. For the unhandled exception of non UI thread, we use the appdomain.unhandledexception event to handle it. For the unhandled exception in task, we use the taskscheduler.unobservedtasexception event to handle it.

For example:

 void App_Startup(object sender, StartupEventArgs e)
 {
     //UI thread exception handling event
     this.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);

     
      //Exception  in task thread
     TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
     //Exception caught by non UI thread
     AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException);
 }





 void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
            try
            {
                e.Handled = true;  
                MessageBox.Show("Exception:" + e.Exception.Message);
            }
            catch (Exception ex)
            {

                MessageBox.Show("error");
            }

   }

    void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {

        }

void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {

            MessageBox.Show("Catch unhandled exception in thread:" + args.Exception.Message);            
            args.SetObserved();//Set the exception to be detected (so that the program will not crash after processing)
        }
Yohann
  • 224
  • 1
  • 7