MonoTouch:未捕获异常处理程序?

7
在MonoTouch中,我如何注册未捕获异常处理程序(或类似的函数)?
在Obj-C中:
void uncaughtExceptionHandler(NSException *exception) {
      [FlurryAnalytics logError:@"Uncaught" message:@"Crash!" exception:exception];
  }

- (void)applicationDidFinishLaunching:(UIApplication *)application { 
     NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
     [FlurryAnalytics startSession:@" "];
    ....
}
3个回答

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

太棒了,谢谢!唯一的问题是接受IntPtr参数的NSException构造函数是受保护的,所以您需要对其进行子类型化并公开该构造函数的版本。否则这非常有帮助。 - Lee Richardson
在这里,您可以看到NSException如何接受一个IntPtr作为参数。 - testing

0

这个可以完成任务。在应用程序启动时调用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);
  }
}

-4

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

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

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


2
这并没有真正回答他最初的问题。 - Nick Berardi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接