0

I have some Xamarin.Mac code that calls a native function as described here. When the function is called it sometimes causes an NSException to be thrown (dependent on connected hardware). Unfortunately the exception isn't caught using try/catch and it crashes my app.

For now I can live with the circumstances that give rise to the exception. However, I cannot live with my app crashing.

I wish to be able to trap when an NSException is thrown, perhaps report an error and continue.

Something like the following would do it:

ExceptionCatcher.CatchExceptionAndGetError(
    () => _platformThing.SometimesThrowException(),
    out var error);

if (error != null)
{
    // Report error
}

// Carry on

I have verified that the exception can be caught when using Objective-C directly.

I am aware of the NSException wrapping solution here. However, before attempting to implement something like this to work with my code, is there something that already exists for Xamarin that I can use to handle this situation?

fractor
  • 1,132
  • 9
  • 26
  • Yes, adding a `ObjCRuntime.Runtime.MarshalObjectiveCException` handler and using `MarshalObjectiveCExceptionMode.ThrowManagedException` gives me an exception I can handle such that my app no longer crashes. You utter, utter beauty. Thank you. You want to post this as an answer? – fractor Oct 14 '19 at 14:10
  • I'm keen to learn and improve. Why the downvote? – fractor Oct 14 '19 at 14:12
  • Glad it helped, I converted the comment to answer. – SushiHangover Oct 14 '19 at 16:37

1 Answers1

1

The Runtime.MarshalManagedException and Runtime.MarshalObjectiveCException events can be used to intercept those exceptions.

Since capturing those exceptions is not performance free features, you have to enable them via the build process (mtouch/mmp):

  • --marshal-managed-exceptions=

    • default
    • unwindnativecode
    • throwobjectivecexception
    • abort
    • disable
  • --marshal-objectivec-exceptions=

    • default
    • unwindmanagedcode
    • throwmanagedexception
    • abort
    • disable

Xamarin has a Exception Marshaling detailed guide that covers both Xamarin.iOS & Mac:

SushiHangover
  • 68,368
  • 9
  • 89
  • 150