Handling Java exceptions in the native layer
While in Java, when an exception is thrown during a method execution, the JVM stops the normal method execution and tries to find an exception handler in the runtime to take control of execution, the same does not apply when you execute the Java method from the JNI code.
The JNI requires developers to explicitly implement the exception handling after an exception has occurred in a Java method invocation.
Moreover, when exception handling is pending, only a few JNI functions are safe to be invoked: DeleteGlobalRef
, DeleteLocalRef
, DeleteWeakGlobalRef
, ExceptionCheck
, ExceptionClear
, ExceptionDescribe
, ExceptionOccurred
, MonitorExit
, PopLocalFrame
, PushLocalFrame
, Release<PrimitiveType>ArrayElements
, ReleasePrimitiveArrayCritical
, ReleaseStringChars
, ReleaseStringCritical
, and ReleaseStringUTFChars
.
There are three ways to handle Java exceptions in a native function.
The first way is to clear the pending exception with ExceptionClear
and continue...