First, catch the exception
Exception handling is a feature in Java that is often used when developing with the SDK in Android. Android native code will need to detect and throw an exception to the Java layer if it encounters an error during execution. There was a problem with the execution of the native code, such as using a null pointer, a memory leak, and without a corresponding detection box exception thrown, the app will immediately flash back without any hint.
Exception handling in JNI is not the same as in Java. Exception handling in Java is directly captured and then handled accordingly. JNI requires developers to explicitly implement exception-handling flows after an exception occurs. For example, the following example:
- Public class Javaclass {
- /**
- * Exception Throw method
- */
- private void ThrowException () throws NullPointerException {
- throw New NullPointerException ("Null pointer");
- }
- /**
- * Native method
- */
- private native void Nativemethod ();
- }
Calling the ThrowException method in native method Nativemethod, Nativemethod native method needs to be displayed to do exception handling. JNI provides the exceptionoccurred function to query whether a virtual machine has a pending exception. After use, 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 allows native code to throw exceptions. Since the exception is a Java class, it is necessary to use the Findclass function to find the exception class in Jni, and a new exception can be initialized and thrown with the Thrownew function. For example:
- 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 execution of the native method. When throwing an exception, you need to release all the resources that have been allocated, such as memory resources ... Local references obtained through the JNIEnv interface are automatically freed by the virtual machine after the native method returns.
Android NDK Development article: Java and Native code communication (Exception handling)