Android - JNI - Recovering MyException members through JNI
In my Java code I create MyException class (extending Exception class) with the getCustomCode() method.
In my C++ code, when I call a Java method that throws MyException I need to execute the getCustomCode of this exception to properly handle the exception.
To accomplish that I execute the Java method that throws MyException with this code:
jint result = env->CallIntMethodA(javaObj, methodId, params);
Right after this line I check for JavaException with this code:
jthrowable exc = env->ExceptionOccurred();
if(exc)
{
jclass objCls = env->FindClass("com/mycompany/myapp/exception/MyException");
jmethodID codeMethod = env->GetMethodID(objCls, "getCustomCode", "()I");
if(!objCls || !codeMethod){ ........ }
// Try to execute getCustomCode java method.
jint codeResult = env->CallIntMethod((jobject)exc, codeMethod);
...
...
}
But, when I try to execute the getCustomCode through JNI it fails. I did some checks with the JNI methods IsAssignableFrom and IsInstanceOf and the result was:
jclass objCls = env->FindClass ("com/mycompany/myapp/exception/MyException");
jclass objThrowable = env->FindClass ("java/lang/Throwable");
if(env->IsAssignableFrom(objCls, objThrowable) == JNI_TRUE) { /* TRUE! */ }
The condition returned true, so my class is correct. Another check:
jclass objCls = env->FindClass ("com/mycompany/m开发者_运维知识库yapp/exception/MyException");
jclass objThrowable = env->FindClass ("java/lang/Throwable");
if(env->IsInstanceOf((jobject)exc, objCls) == JNI_TRUE) { /* FALSE */ }
if(env->IsInstanceOf((jobject)exc, objThrowable) == JNI_TRUE) { /* FALSE */ }
Both conditions returned false, so neither MyException nor Throwable is the exc class!
So, what is the jthrowable object? And how can I cast the jthrowable object to a jobject to access MyException members? Is it possible?
Thank you!
Most likely you need to call env->ExceptionClear()
before env->FindClass(...)
etc. You are not allowed to call most JNI methods while an exception is active, see section 6.2.2 of this page. List of allowed functions when there is a pending exception:
ExceptionOccurred
ExceptionDescribe
ExceptionClear
ExceptionCheck
ReleaseStringChars
ReleaseStringUTFchars
ReleaseStringCritical
Release<Type>ArrayElements
ReleasePrimitiveArrayCritical
DeleteLocalRef
DeleteGlobalRef
DeleteWeakGlobalRef
MonitorExit
精彩评论