In my C code, I want to test for a Java exception, get information about it, and handle it locally:
jobject exc = env->ExceptionOccurred();
if (exc) {
env->ExceptionClear();
jclass javaLang = env->FindClass("java/lang/Object");
jmethodID j_toString = env->GetMethodID(javaLang, "toString", "()Ljava/lang/String;");
auto s = (jstring)(env->CallObjectMethod(exc, j_toString));
...
}
I call ExceptionClear()
right near the top because the call to FindClass()
will cause a "JNI FindClass called with pending exception" error if I don't. But if I do this, will the exception object still be valid?
CodePudding user response:
ExceptionOccurred
gives you a local reference to the exception object. So it's not going to be affected by ExceptionClear
unless ExceptionClear
also clears the local reference table, which would be weird (neither ART nor Dalvik does that FWIW).
I think you can safely assume that exc
is still valid after ExceptionClear
. And if it isn't, you'd notice it because you'd get some kind of JNI error for using a stale local reference.