test test
test test

Reputation: 85

Android JNI exception handling

I need an exception handling implemented in JNI code. I am not good at jni and can't find any good example. So, please provide full example for this.

This is what I am doing:

jint JNI_OnLoad(JavaVM* vm, void* reserved) {
    jint result = -1;
    g_JavaVM = vm;

    if (vm->GetEnv((void **) &envLocal, JNI_VERSION_1_6) != JNI_OK) {

        return -1;
    }

    jclass clazz;
    **clazz = envLocal->FindClass("com/graphics/myclass/MyClass");**
    if (clazz == NULL)
        __android_log_print(ANDROID_LOG_ERROR, "MyClass",
                "clazz value is null");
    g_clazz = (jclass) envLocal->NewGlobalRef(clazz);

    // STEP 3/3 : Delete the no longer needed local reference
    envLocal->DeleteLocalRef(clazz);
    result = JNI_VERSION_1_6;
    return result;
}

Now I have a need where if this MyClass is not available (because app developer does not have corresponding jar file) then, there should not be any app crash. JNI_OnLoad will be called when loading a library using System.LoadLibrary("libmyclass.so") and this "com/graphics/myclass/MyClass" class.

Currently, if this jar is not included in the app this causes and app to crash with below exception

F/art     (14708): sart/runtime/check_jni.cc:65] JNI DETECTED ERROR IN APPLICATION: JNI NewGlobalRef called with pending exception 'java.lang.ClassNotFoundException' thrown in unknown throw location
F/art     (14708): sart/runtime/check_jni.cc:65]     in call to NewGlobalRef
F/art     (14708): sart/runtime/check_jni.cc:65]     from java.lang.String java.lang.Runtime.nativeLoad(java.lang.String, java.lang.ClassLoader, java.lang.String)
F/art     (14708): sart/runtime/check_jni.cc:65] "main" prio=5 tid=1 Runnable

What I need is rather this exception handled by android somewhere, it should be handled in JNI_OnLoad so that app does not crash. I don't want exception handling by java.

so my thinking is if I catch exception thrown by " clazz = envLocal->FindClass("com/graphics/systemOp/SystemOp");" be handled in JNI_OnLoad after this.

Can someone suggest an example (complete one) because I can't implement it. With full source code please. Ask me if you need more information.

Upvotes: 4

Views: 6633

Answers (1)

marcinj
marcinj

Reputation: 49986

You can call following code after doing jni operations that may throw:

bool checkExc(JNIEnv* env) {
 if(env->ExceptionCheck()) {
  env->ExceptionDescribe(); // writes to logcat
  env->ExceptionClear();
  return true;
 }
 return false;
}

Upvotes: 6

Related Questions