如何尝试/捕获所有异常 [英] How to try/catch all exceptions

查看:328
本文介绍了如何尝试/捕获所有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在完成由别人开始的UWP应用程序。应用程序经常崩溃,我总是在 App.gics

  if(global: :System.Diagnostics.Debugger.IsAttached)
global :: System.Diagnostics.Debugger.Break();

然后我不得不说不,不启动调试器并关闭2个窗口。



有没有什么地方可以放一个大的try / catch,这样我就不必每次重启这个应用程序?在 AppShell App 中找不到任何内容。



或者我必须在每个事件处理程序中放一个try / catch?

解决方案

如果要避免每次遇到未处理的异常时启动新的调试器并重新启动应用程序,可以使用 Application.UnhandledException事件 ,并设置 处理 属性事件参数为true,如下所示:

  public App()
{
this.InitializeComponent();
this.Suspending + = OnSuspending;
this.UnhandledException + =(sender,e)=>
{
e.Handled = true;
System.Diagnostics.Debug.WriteLine(e.Exception);
};
}




UnhandledException 事件用于通知应用程序关于XAML框架或Windows运行时一般没有被应用程序代码处理的异常。



通常在 UnhandledException 事件被触发,Windows运行时终止应用程序,因为异常未被处理。应用代码对此有一些控制权:如果 UnhandledException 事件处理程序设置真实的Windows.ui.xaml.unhandledexceptioneventargs.handled.aspxrel =noreferrer> 处理 属性,那么在大多数情况下


有关更多信息,请参阅备注 ://msdn.microsoft.com/en-us/library/windows/apps/xaml/windows.ui.xaml.application.unhandledexception.aspxrel =noreferrer> Application.UnhandledException事件和博客:在Windows Store应用程序中处理错误的策略


I'm completing a UWP app started by someone else. The app crashes frequently and I always end up in App.g.i.cs at

if (global::System.Diagnostics.Debugger.IsAttached)
    global::System.Diagnostics.Debugger.Break(); 

where I then have to say "no, don't start the debugger" and close 2 windows.

Is there somewhere I could put a big try/catch so that I don't have to restart the app each time this happen? I can't find anything in AppShell or App.

Or do I have to put a try/catch in every single event handler?

解决方案

If you want to avoid starting the new debugger and restarting the app each time when encountering unhandled exceptions, you can use Application.UnhandledException event and set the Handled property of the event arguments to true like following:

public App()
{
    this.InitializeComponent();
    this.Suspending += OnSuspending;
    this.UnhandledException += (sender, e) =>
    {
        e.Handled = true;
        System.Diagnostics.Debug.WriteLine(e.Exception);
    };
}

The UnhandledException event is used to notify the app about exceptions encountered by the XAML framework or by the Windows Runtime in general that have not been handled by app code.

Normally after the UnhandledException event is fired, the Windows Runtime terminates the app because the exception was unhandled. The app code has some control over this: if the UnhandledException event handler sets the Handled property of the event arguments to true, then in most cases the app will not be terminated.

For more info, please see Remarks of Application.UnhandledException event and the blog: Strategies for Handling Errors in your Windows Store Apps.

这篇关于如何尝试/捕获所有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆