MonoTouch: uncaughtExceptionHandler?

本文关键字:uncaughtExceptionHandler MonoTouch | 更新日期: 2023-09-27 18:26:01

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

在对象C:中

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

MonoTouch: uncaughtExceptionHandler?

    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部分。但到那时,该应用程序将处于一种奇怪的状态,产生不可预测的影响。因此,我强烈建议在用户决定如何处理异常后杀死该应用程序——例如,通过重新抛出它

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);
  }
}

在可能抛出NSException:的代码周围添加一个try-catch处理程序

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

MonoTouch已经安装了一个未捕获的异常处理程序,并自动将这些ObjectiveC异常转换为托管异常。

相关文章:
  • 没有找到相关文章