简体   繁体   中英

C# WPF unhandled exception: how to make the most of it

I am quite new to WPF but find AMAZING to be able to trap any unhandled exception. I have put

this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;

in the constructor of my class. This leads me to trap it with

private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
  e.Handled = true;
  ...
}

At first it didn't work but then I've seen that to make it work I have to run it in release and outside VS IDE. So that works.

What I'd like is to get as much as info as possible about what caused the exception. Possibly the exception type, the s/r, the line and whatever else is provided.

At the moment by doing

 int a = 0;
 int b = 3 / a;

and by putting

MessageBox.Show(e.ToString() + "  " + sender.ToString());

I get:

在此处输入图片说明

so that's not the right way.

I know that I am not putting the necessary information in the question but I have searched through various answer but none reported what I need. If so it can be useful to save any data prior closing but not about closing but not to detected what caused the exception

What's more when I exit with

Environment.Exit(-1)

I find the process still running and that's a problem. Here Terminate application after unhandled exception it says that I have to kill my process is it really the right way to close my application after an unhandled exception?

Thanks for any help

The actual exception that caused the application to crash is wrapped inside the DispatcherUnhandledExceptionEventArgs parameter.

Simply use e.Exception to get hold of it.

MessageBox.Show(e.Exception.ToString());

After displaying the exception, I would suggest allowing the application to continue by calling the base method:

base.OnUnhandledException(sender, e);

You may choose to mark the exception as handled of course, however in the case of when you are simply overriding this method to display the error, I would not count that as handled .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM