提升NSUncaughtExceptionHandler的异常

时间:2016-05-30 16:29:52

标签: c# ios xamarin exception-handling xamarin.ios

我想测试material2 = material1.clone(); 的实现。我尝试了什么:

NSUncaughtExceptionHandler

这是我在 AppDelegate.cs 中的实现:

int[] array = new int[3];
array[4] = 1;

object o = null;
o.GetHashCode();

没有抓住异常。如何引发public delegate void NSUncaughtExceptionHandler(IntPtr handle); [DllImport("/System/Library/Frameworks/Foundation.framework/Foundation")] private static extern void NSSetUncaughtExceptionHandler(IntPtr handle); public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); NSSetUncaughtExceptionHandler(Marshal.GetFunctionPointerForDelegate(new NSUncaughtExceptionHandler(MyUncaughtExceptionHandler))); return base.FinishedLaunching(app, options); } [MonoPInvokeCallback(typeof(NSUncaughtExceptionHandler))] private static void MyUncaughtExceptionHandler(IntPtr handle) { NSException exception = (NSException)ObjCRuntime.Runtime.GetNSObject(handle); } 可以捕获的异常?

1 个答案:

答案 0 :(得分:1)

现实世界例外如何:NSInvalidArgumentException(由于无法识别的选择器)

声明消息发送签名:

[DllImport(Constants.ObjectiveCLibrary, EntryPoint = "objc_msgSend")]
static extern CGSize cgsize_objc_msgSend_IntPtr_float_int_foobar(IntPtr target, IntPtr selector, IntPtr font, nfloat width, UILineBreakMode mode);

异常处理程序:

[MonoPInvokeCallback(typeof(NSUncaughtExceptionHandler))]
private static void MyUncaughtExceptionHandler(IntPtr handle)
{
    NSException exception = (NSException)ObjCRuntime.Runtime.GetNSObject(handle);
    Console.WriteLine(exception);
    Console.WriteLine(exception.CallStackSymbols[0]);
}

拨打有效且无效的电话:

    public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
    {
        // Override point for customization after application launch.
        // If not required for your application you can safely delete this method
        NSSetUncaughtExceptionHandler(Marshal.GetFunctionPointerForDelegate(new NSUncaughtExceptionHandler(MyUncaughtExceptionHandler)));

NSString target = new NSString("StackOverFlow");
Selector selector = new Selector("sizeWithFont:forWidth:lineBreakMode:");
UIFont font = null;
nfloat width = 1.0f;
UILineBreakMode mode = UILineBreakMode.CharacterWrap;
CGSize size = cgsize_objc_msgSend_IntPtr_float_int_foobar( target.Handle, selector.Handle, font == null ? IntPtr.Zero : font.Handle, width, mode);

// `NSInvalidArgumentException` (due to unrecognized selector)
selector = new Selector("StackOverFlowSelector:");
size = cgsize_objc_msgSend_IntPtr_float_int_foobar(target.Handle, selector.Handle, font == null ? IntPtr.Zero : font.Handle, width, mode);

return true;

}

输出:

-[__NSCFString StackOverFlowSelector:]: unrecognized selector sent to instance 0x7cb0a4e0
0   CoreFoundation                      0x00976494 __exceptionPreprocess + 180

注意:

请记住,您正在回调托管代码以捕获非托管异常,这确实应该在ObjC库中完成..