shannah / Java-Objective-C-Bridge

A thin bridge that allows for two-way communication from Java to Objective-C.
123 stars 25 forks source link

Catch all errors in native code and throw Java exceptions #8

Open mojo2012 opened 5 years ago

mojo2012 commented 5 years ago

Hi there,

I'm trying to implement a generic error handling in the native library like this:

-(void) throwJavaException:(JNIEnv *)env withMessage: (const char *)msg
{
    // You can put your own exception here
    jclass c = (*env)->FindClass(env, "java/lang/RuntimeException");

    (*env)->ThrowNew(env, c, msg);
}

And wrapped all functions/methods/selectors in WLJavaProxy.m into this try catch:

@try
    {
         ....
    } @catch (NSException *e) {
        [self throwJavaException: env withMessage: [[e reason] UTF8String] ];
        NSLog(@"Exception: %@", e);
    }

The hope was that for any error that occurred in native code, the VM would not crash but rather show a RuntimeException.

Is this the correct approach to do this? It would be nice to have such a thing to prevent crashes!

shannah commented 5 years ago

That would be useful. Your approach looks fine. With anything JNI related, there may be some corner cases that make it more difficult, but you'll have to wait for those cases to present themselves.

mojo2012 commented 5 years ago

I'll try to produce a test scenario and make a PR. Btw, it would be awesome to have the library on maven central!