MonoTouch:uncaughtExceptionHandler?

在MonoTouch中,如何注册未捕获的exception处理程序(或类似函数)

在Obj-C中:

void uncaughtExceptionHandler(NSException *exception) { [FlurryAnalytics logError:@"Uncaught" message:@"Crash!" exception:exception]; } - (void)applicationDidFinishLaunching:(UIApplication *)application { NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler); [FlurryAnalytics startSession:@" "]; .... } 

你可以在(可能)抛出NSExceptions的代码周围添加一个try-catch处理程序:

 try { FlurryAnalytics.StartSession (" "); } catch (MonoTouchException ex) { Console.WriteLine ("Could not start flurry analytics: {0}", ex.Message); } 

MonoTouch已经安装了未捕获的exception处理程序,并自动将这些ObjectiveCexception转换为托管exception。

  public delegate void NSUncaughtExceptionHandler(IntPtr exception); [DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")] private static extern void NSSetUncaughtExceptionHandler(IntPtr handler); // This is the main entry point of the application. private static void Main(string[] args) { NSSetUncaughtExceptionHandler( Marshal.GetFunctionPointerForDelegate(new NSUncaughtExceptionHandler(MyUncaughtExceptionHandler))); ... } [MonoPInvokeCallback(typeof(NSUncaughtExceptionHandler))] private static void MyUncaughtExceptionHandler(IntPtr exception) { var e = new NSException(exception); ... } 

这样做了。 在应用启动时调用SetupExceptionHandling()方法。 神奇的是NSRunLoop部分。 但该应用程序将在那时处于一种奇怪的状态,具有不可预测的影响。 因此,我强烈建议在用户决定如何处理exception后杀死应用程序 – 例如,通过重新抛出它。

 public static class IOSStartupTasks { private static bool _HaveHandledException; public static void HandleException(object sender, UnhandledExceptionEventArgs e) { if (!(_HaveHandledException)) { _HaveHandledException = true; UIAlertView alert = new UIAlertView("Error", "Bad news", "report", "just crash"); alert.Delegate = whatever; // delegate object should take the exception as an argument and rethrow when it's done handling user input. alert.Show(); NSRunLoop.Current.RunUntil(NSDate.DistantFuture); // keeps the app alive, but likely with weird effects, so make sure you don't let the user back into the main app. } } public static void SetupExceptionHandling() { AppDomain domain = AppDomain.CurrentDomain; domain.UnhandledException += (object sender, UnhandledExceptionEventArgs e) => IOSStartupTasks.HandleException(sender, e); } }