c# – 如何尝试/捕获所有异常

我正在完成由其他人启动的UWP应用程序.该应用程序经常崩溃,我总是在App.g.i.cs中结束

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

然后,我必须说“不,不要启动调试器”并关闭2个窗口.

有什么地方我可以放一个大尝试/捕获,这样我不必每次都发生时重启应用程序?我在AppShell或App中找不到任何东西.

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

解决方法:

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

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 07001 property of the event arguments to true, then in most cases the app will not be terminated.

有关详细信息,请参阅Application.UnhandledException event的备注和博客:Strategies for Handling Errors in your Windows Store Apps.

上一篇:c# – UWP app:FileOpenPicker PickSingleFileAsync()无法等待


下一篇:c# – 无法连接到StreamSocketListener