Avoid Mac app crashing after unhandled exception

China☆狼群 提交于 2021-02-08 17:07:25

问题


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

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;

And log it:

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

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

NSApplication.Main(args);

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


回答1:


This is what the xamarin developer center has to say:

"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)."

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.




回答2:


Ok, i know this is a little bit old but i was struggle with this too for many months, since my app crashed without any stack trace... but! ... i figure it out after many try and catch here and there, that you can put in the constructor of your AppDelegate.cs class the following:

            AppDomain.CurrentDomain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => {
                Exception GivenException = (Exception) e.ExceptionObject;
                Console.WriteLine( GivenException.Message);
                Console.WriteLine( GivenException.StackTrace);
                Console.WriteLine("Runtime terminating: {0}", e.IsTerminating);
            };

This will not avoid the app for terminate but at least you will know exactly where to look and fix the issues.



来源:https://stackoverflow.com/questions/23909348/avoid-mac-app-crashing-after-unhandled-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!