知道何时从 Xamarin 抛出 NSException
Know when NSException is thrown from Xamarin
我有一些 Xamarin.Mac 代码调用本机函数 as described here。当函数被调用时,它有时会导致抛出 NSException(取决于连接的硬件)。不幸的是,使用 try/catch 没有捕获异常,它使我的应用程序崩溃。
现在我可以忍受导致异常的情况。但是,我不能忍受我的应用程序崩溃。
我希望能够在抛出 NSException 时进行捕获,也许会报告错误并继续。
像下面这样的东西可以做到:
ExceptionCatcher.CatchExceptionAndGetError(
() => _platformThing.SometimesThrowException(),
out var error);
if (error != null)
{
// Report error
}
// Carry on
我已经验证直接使用Objective-C可以捕捉到异常。
我知道 NSException 包装解决方案 。但是,在尝试实现类似的功能以使用我的代码之前,Xamarin 是否已经存在一些我可以用来处理这种情况的东西?
Runtime.MarshalManagedException
和 Runtime.MarshalObjectiveCException
事件可用于拦截这些异常。
由于捕获这些异常不是性能无关的功能,因此您必须通过构建过程启用它们 (mtouch/mmp):
--marshal-managed-exceptions=
- 默认
- unwindnativecode
- 抛出目标异常
- 中止
- 禁用
--marshal-objectivec-exceptions=
- 默认
- unwindmanagedcode
- 抛出管理异常
- 中止
- 禁用
Xamarin 有一个异常封送处理的详细指南,涵盖了 Xamarin.iOS 和 Mac:
我有一些 Xamarin.Mac 代码调用本机函数 as described here。当函数被调用时,它有时会导致抛出 NSException(取决于连接的硬件)。不幸的是,使用 try/catch 没有捕获异常,它使我的应用程序崩溃。
现在我可以忍受导致异常的情况。但是,我不能忍受我的应用程序崩溃。
我希望能够在抛出 NSException 时进行捕获,也许会报告错误并继续。
像下面这样的东西可以做到:
ExceptionCatcher.CatchExceptionAndGetError(
() => _platformThing.SometimesThrowException(),
out var error);
if (error != null)
{
// Report error
}
// Carry on
我已经验证直接使用Objective-C可以捕捉到异常。
我知道 NSException 包装解决方案
Runtime.MarshalManagedException
和 Runtime.MarshalObjectiveCException
事件可用于拦截这些异常。
由于捕获这些异常不是性能无关的功能,因此您必须通过构建过程启用它们 (mtouch/mmp):
--marshal-managed-exceptions=
- 默认
- unwindnativecode
- 抛出目标异常
- 中止
- 禁用
--marshal-objectivec-exceptions=
- 默认
- unwindmanagedcode
- 抛出管理异常
- 中止
- 禁用
Xamarin 有一个异常封送处理的详细指南,涵盖了 Xamarin.iOS 和 Mac: