本文介绍了如果不知道发生在哪里,如何在应用程序范围内捕获未处理的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用M-V-VM方法编写的应用程序.如果ViewModel中引发了异常,然后,应用程序范围的Application.DispatcherUnhandledException处理程序无法捕获异常.

I have an application written using the M-V-VM approach. If the exception is throwed in the ViewModel,  Then the application wide Application.DispatcherUnhandledException handler cannot catch the exceptions.

我读到有人说你需要像这样重新扔他们:
尝试                       
{
...
}           
catch(例外情况除外)                       
{                        
  ApplicationException exWrapper = new ApplicationException("Wrapped Exception",ex);          nbsp; b
 动作throwException =()=> {投掷exWrapper; };                        
  Dispatcher.CurrentDispatcher.BeginInvoke(throwException);          b
}

I read someone says that you need to re-throw them like this:
try            
{
...
}            
catch (Exception ex)            
{               
 ApplicationException exWrapper = new ApplicationException("Wrapped Exception", ex);                
 Action throwException = () => { throw exWrapper; };                
 Dispatcher.CurrentDispatcher.BeginInvoke(throwException);                
}

但是,我不知道异常发生的时间和地点,因此我不知道在哪里包装这样的包装.如果在任何属性或函数中放入包装器,则可能会导致过大杀伤力. WPF为什么不像WinForm那样运行,所以我们可以在DispatcherUnhandledException中捕获这些异常. 自动运行,应用程序可以正常退出吗?

However, I don't know when and where the exception will happen so I have no idea where to a wrapper like this. If put a wrapper in any Property or function then it will be overkill. Why don't WPF act like WinForm so we can catch these exception in DispatcherUnhandledException automatically and the application can exit gracefully?

有人知道怎么做吗?

Gordon高级软件开发人员

Gordon Senior Software Developper

推荐答案

实际上,您还可以处理另外两个异常,这些异常可以捕获其他类型的未处理异常:

There's actually two other exceptions you can handle that catch other types of unhandled exceptions further down:

            AppDomain currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);

            TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);

我们将这三个功能都发挥了很大的作用.

We use all three to great effect.

此致,
佩德罗(Pedro)

Regards,
Pedro


这篇关于如果不知道发生在哪里,如何在应用程序范围内捕获未处理的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 22:59