I want to handle all unexpected errors in a WPF application. When I look at, there are different events for different situation to capture and control error. Also I added these in application constructor method
public App()
{
AppDomain.CurrentDomain.FirstChanceException += OnFirstChanceException;
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
Dispatcher.UnhandledException += OnDispatcherUnhandledException;
TaskScheduler.UnobservedTaskException += OnUnobservedTaskException;
}
However, I try that for checking handling but they didn't work. What is the reason?
private void btnStart_Click(object sender, RoutedEventArgs e) //2021112242
{
throw new StackOverflowException();
}
Every exception event has his own callback method & event object
// Dispatcher.UnhandledException
private static void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
}
// TaskScheduler.UnobservedTaskException
private static void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
}
// AppDomain.CurrentDomain.UnhandledException
private static void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
}
// AppDomain.CurrentDomain.FirstChanceException
private static void OnCurrentDomainUnhandledException(object sender, FirstChanceExceptionEventArgs e)
{
}
App
has an event for this called DispatcherUnhandledException
. This works in most cases but when the exception is thrown from a separate thread it gets a little hairy.
public partial class App
{
public App()
{
// Globally handle errors/exceptions for a friendly close.
DispatcherUnhandledException += DispatcherOnUnhandledException;
}
private void DispatcherOnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
try
{
e.Handled = true;
e.Exception.Display("An unhandled exception occurred, the application will now close.");
e.Exception.Log(); // log the problem.
Shutdown(-1); // assume not recoverable.
}
catch
{
Shutdown(-1);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.