在MonoTouch中,如何注册未捕获的异常处理程序(或类似函数)
在Obj-C中:
void uncaughtExceptionHandler(NSException *exception) {
[FlurryAnalytics logError:@"Uncaught" message:@"Crash!" exception:exception];
}
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
[FlurryAnalytics startSession:@" "];
....
}
答案 0 :(得分:2)
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);
...
}
答案 1 :(得分: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);
}
}
答案 2 :(得分:-4)
在代码周围添加一个try-catch处理程序(可能)抛出NSExceptions:
try {
FlurryAnalytics.StartSession (" ");
} catch (MonoTouchException ex) {
Console.WriteLine ("Could not start flurry analytics: {0}", ex.Message);
}
MonoTouch已安装未捕获的异常处理程序,并自动将这些ObjectiveC异常转换为托管异常。