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)
}