我想测试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);
}
可以捕获的异常?
答案 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库中完成..