首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MonoTouch: uncaughtExceptionHandler?

MonoTouch: uncaughtExceptionHandler?
EN

Stack Overflow用户
提问于 2012-02-29 08:11:34
回答 3查看 2.3K关注 0票数 7

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

在Obj-C中:

代码语言:javascript
复制
void uncaughtExceptionHandler(NSException *exception) {
      [FlurryAnalytics logError:@"Uncaught" message:@"Crash!" exception:exception];
  }

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-02-29 08:51:11

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

代码语言:javascript
复制
try {
    FlurryAnalytics.StartSession (" ");
} catch (MonoTouchException ex) {
    Console.WriteLine ("Could not start flurry analytics: {0}", ex.Message);
}

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

票数 -4
EN

Stack Overflow用户

发布于 2015-06-16 21:49:37

代码语言:javascript
复制
    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);
        ...
    }
票数 3
EN

Stack Overflow用户

发布于 2016-08-28 03:45:23

这就完成了工作。在应用启动时调用SetupExceptionHandling()方法。神奇之处在于NSRunLoop部分。但在这一点上,应用程序将处于一种奇怪的状态,具有不可预测的影响。因此,我强烈建议在用户决定如何处理异常之后终止应用程序--例如,通过重新抛出它。

代码语言:javascript
复制
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);
  }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9491813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档