ssk
ssk

Reputation: 9255

How to throw an exception from C while using Android NDK?

I have a random crash in my app deep inside the C++/C NDK layer. Backtraces are not helpful from Google Play Console.

Here is the backtrace:

#00 pc 000000000004bba8 /system/lib/libc.so (tgkill+12) 
#01 pc 000000000001aa13 /system/lib/libc.so (abort+54) 
#02 pc 000000000001f2f9 /system/lib/libc.so (__libc_fatal+24) 
#03 pc 000000000001aedd /system/lib/libc.so (__assert2+16) 

I am considering to change assert to in my assert wrapper to throw an exception instead.

I saw suggestions from: How to throw an exception in C? and not sure it's applicable for Android (portability to iOS as well.).

Upvotes: 1

Views: 1647

Answers (2)

shizhen
shizhen

Reputation: 12583

You can throw Java Exception, e.g. IllegalArgumentException, from JNI layer like below:

//JNIEnv *env,

jclass jcls = env->FindClass("java/lang/IllegalArgumentException");
env->ThrowNew(jcls, "Argument cannot be null.");

Also, you can check Exception status in JNI layer like below:

//JNIEnv *env,

jboolean flag = env->ExceptionCheck();
if (flag) {
    env->ExceptionClear();
    /* code to handle exception */
}

Upvotes: 2

Elliott Hughes
Elliott Hughes

Reputation: 206

You want to clarify that you mean throwing a Java exception, for which you want JNI. Specifically the JNI ThrowException function.

Any docs you find about throwing exceptions from JNI will apply to Android. (But none of this will work on iOS.)

Upvotes: 1

Related Questions