First, catch the exception
Exception handling is a feature in Java. It is often used when developing with the SDK in Android. Android native code assumes errors during operation, requires a test, and throws an exception to the Java layer. There was a problem running native code, such as using a null pointer and a memory leak. And did not make the corresponding check box exception thrown. The app will instantly flash back. No matter what the hint.
Exception handling in JNI is not the same as in Java. Exception handling in Java is the direct capture and then the corresponding processing.
JNI requires developers to explicitly implement exception-handling flows after an exception occurs. The proportions are shown in the following example:
public class Javaclass {/** * exception throw method */private void ThrowException () throws NullPointerException {throw new Nullpointerexc Eption ("Null pointer");} /** * Native method */private native void Nativemethod ();}
The ThrowException method is called in native method Nativemethod. Nativemethod native methods need to be displayed for exception handling. JNI provides the exceptionoccurred function to query whether a virtual machine has a pending exception.
After the use is complete. The Exceptionclear function is also required to explicitly clear the exception.
Jthrowable ex;//... (*env)->callvoidmethod (env, instance, Throwexceptionid); ex = (*env)->exceptionoccurred (env); if (0! = ex) { ( *ENV)->exceptionclear (env);}
Second, throw an exception
JNI also agrees that the native code throws an exception. Because exceptions are Java classes, you need to use the Findclass function in JNI to find the exception class. You can initialize and throw a new exception with the Thrownew function. Like what:
Jclass Clazz;//...clazz = (*env)->findclass (env, "java/lang/nullpointerexception"); if (0! = clazz) { (*env)- >thrownew (env, Clazz, "Exception message.");
Because the native method is not controlled by the virtual machine, the exception thrown does not stop the native method from running. When you throw an exception. Need to release all the resources that have been allocated, such as memory resources ... Local references obtained through the JNIEnv interface are released by the virtual machine itself after the native method returns.
Android NDK Development Chapter (VI): Java and Native code communication (Exception handling)