简体   繁体   English

C#WPF未处理的异常:如何充分利用它

[英]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. 我对WPF还是很陌生,但是发现AMAZING能够捕获任何未处理的异常。 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. 最初,它不起作用,但后来我看到要使其起作用,我必须在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. 可能是异常类型,s / r,行以及提供的其他任何内容。

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. 导致应用程序崩溃的实际异常包含在DispatcherUnhandledExceptionEventArgs参数中。

Simply use e.Exception to get hold of it. 只需使用e.Exception即可掌握它。

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

After displaying the exception, I would suggest allowing the application to continue by calling the base method: 显示异常后,建议通过调用base方法允许应用程序继续运行:

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 . 您当然可以选择将异常标记为已处理,但是在仅覆盖此方法以显示错误的情况下,我不会将其视为已处理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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