避免 Mac 应用程序在未处理的异常后崩溃 [英] Avoid Mac app crashing after unhandled exception

查看:32
本文介绍了避免 Mac 应用程序在未处理的异常后崩溃的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止我的应用在引发未处理的异常后关闭.

I want to prevent my app from closing after an unhandled exception has been raised.

我正在用 Xamarin 和 MonoMac 做这件事,但我想我可以将 Objective-C 的答案翻译成 C#.

I'm doing this with Xamarin and MonoMac, but I think I could translate Objective-C answers to C#.

当异常发生并且没有在任何地方被捕获时,我注册未处理异常的事件:

When an Exception happens and it's not caught anywhere, I register the event of unhandled exceptions:

AppDomain.CurrentDomain.UnhandledException += HandleUnhandledException;

并记录它:

static void HandleUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
    //Log the exception...
}

但是,当发生异常时,会执行 HandleUnhandledException 并退出事件循环:

But then, when an exception happens, the HandleUnhandledException is executed and the event loop is exited:

NSApplication.Main(args);

所以我的应用程序结束.我怎样才能避免这种情况?我应该在哪里放置 try-catch 块?

So my app ends. How can I avoid this? Where should I place a try-catch block?

推荐答案

这是 xamarin 开发者中心不得不说的:

This is what the xamarin developer center has to say:

"您可以为 AppDomain.CurrentDomain.UnhandledException 事件添加一个事件处理程序,当发生未处理的托管异常时,您将收到通知(注意,应用程序将在您无论你做什么,从你的事件处理程序返回,唯一的目的就是让你收集诊断信息.而且它只会捕获托管异常,而不是本机崩溃,这是退出应用程序的另一个原因)."

"You can add an event handler to the AppDomain.CurrentDomain.UnhandledException event, and you will get notified when unhandled managed exceptions occur (note that the app will exit as soon as you return from your event handler no matter what you do so pretty much the only purpose would be for you to collect diagnostic information. Also it will only catch managed exceptions, not native crashes, which is another cause of exiting apps)."

因此,显然,您可以添加一个全局 try catch 块,但这只是告诉您有关托管异常的信息,应用程序将在 try catch 结束时退出.所以它不会完全达到你的目的.

So, apparently, yo can add a global try catch block but that will just be to tell you about the managed exceptions and the app will exit by the end of the try catch. So it won't serve your purpose fully.

这篇关于避免 Mac 应用程序在未处理的异常后崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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