What returns the Java method to the calling JNI when it throws an exception?

Let's say I have the following Java code:

public class Test { public static int foo() { throw new RuntimeException(); } } 

which loads its own library in the usual way. The native library registers and caches the JVM or something else, and then, later, this function is executed:

 JNIEnv* sEnv; // initialised somewhere properly void throwMeARiver() { jclass c = sEnv->FindClass("Test"); jmethodID m = sEnv->GetStaticMethodID(c, "foo", "()I"); jint i = sEnv->CallStaticIntMethod(c, m); printf("Got %d\n", (int)i); } 

Obviously, sEnv-> CheckException () will now return JNI_TRUE, but what comes of the native function? In Java, throwing an exception, the JVM stops the method until it finds the appropriate handler, so the return value of foo () will be undefined. Am I also undefined?

I can not find any specifications or anything that says otherwise, so presumably i / is / undefined. In this case, there is no โ€œnormalโ€ CallStaticIntMethod range, unlike most JNI functions.

I'm trying to do this now, but I basically ask for it to see if there is any specific behavior somewhere.

+6
source share
2 answers

While the variable I will be defined, its value is not defined. In this situation, most likely the value will be 0, but only if the JVM initialized the value in its implementation. Otherwise, it will be equal to the fact that the data is present in its location in memory.

Its up to the native function executor to correctly check the exception following CallXXXMethod() via env->CheckException() , env->ExceptionOccurred() and env->ExceptionDescribe() . Finally, call env->ClearException() to remove the exception.

+2
source

No, JNI CheckException () is not equivalent to Java try ... catch, so your new RuntimeException() will propagate further and may not fall at all.

Thanks to @EJP for correcting me: in fact, any Throwable from Java is intercepted by the C / C ++ caller. From my Android tests, the return value is what happens in some unpredictable memory location (stack?).

For more information on JNI and exceptions, see How to catch a JNI / Java exception .

-1
source

Source: https://habr.com/ru/post/955039/


All Articles