## exception handling
Exception test examples:
public native void testException1(); public static void main(String[] args) { JniTest test = new JniTest(); try { test.testException(); System.out.println(" program cannot proceed with 1, this sentence will not be printed \n"); } catch (Throwable t) {system.out.println (" catch an exception thrown by JNI (Throwable), this will be printed "+ t.getmessage () + "\n"); } system.out.println (" program continues to execute 2, this sentence will be printed \n"); }Copy the code
C code is as follows:
JNIEXPORT void JNICALL Java_com_test_JniTest_testException1 (JNIEnv * env, jobject jobj){ jclass clz= (*env)->GetObjectClass(env, jobj); JfieldID fid = (*env)->GetFieldID(env, CLZ, "key1", "Ljava/lang/String; ); Printf ("C can run, this will print"); printf("C can run, this will print"); Jstring key = (*env)->GetObjectField(env, jobj, fid) Char * c_str = (*env)->GetStringUTFChars(env, key, NULL); printf("C could not run , this will not print"); }Copy the code
As you can see from the examples, the JNI layer throws an exception of the Error type. Java can catch the exception through Throwable or Error. After catching the exception, Java code can continue to execute.
In order to ensure that Java, C/C++ code can execute properly, you need to:
- Manually clear ExceptionClear in the JNI layer to ensure that the code can run.
- Remedies ensure that C/C++ code continues to run.
Such as:
JNIEXPORT void JNICALL Java_com_test_JniTest_testException1 (JNIEnv * env, jobject jobj){ jclass clz = (*env)->GetObjectClass(env, jobj); JfieldID fid = (*env)->GetFieldID(env, CLZ, "key1", "Ljava/lang/String; ); jthrowable err = (*env)->ExceptionOccurred(env); if (err ! (*env)->ExceptionClear(env); Fid = (*env)->GetFieldID(env, CLZ, "key", "Ljava/lang/String;" ); } jstring key = (*env)->GetObjectField(env, jobj, fid); char* c_str = (*env)->GetStringUTFChars(env, key, NULL); }Copy the code
The test code is as follows:
public static void main(String[] args) { JniTest test = new JniTest(); try { test.testException(); System.out.println(" There is no exception in the program, this sentence will be printed \n"); } catch (Exception e) {system.out.println (" JNI Exception not caught, this will not be printed "+ LLDB message () + "\n"); } system.out.println (" Program continues, this sentence will be printed \n"); }Copy the code
The user can manually throw an exception through the ThrowNew function, which can also be caught by Java code:
JNIEXPORT void JNICALL Java_com_test_JniTest_testException (JNIEnv * env, jobject jobj){ jclass clz = (*env)->GetObjectClass(env, jobj); JfieldID fid = (*env)->GetFieldID(env, CLZ, "key1", "Ljava/lang/String; ); jthrowable err = (*env)->ExceptionOccurred(env); if (err ! (*env)->ExceptionClear(env); Fid = (*env)->GetFieldID(env, CLZ, "key", "Ljava/lang/String;" ); } jstring key = (*env)->GetObjectField(env, jobj, fid); char* c_str = (*env)->GetStringUTFChars(env, key, NULL); If (_stricmp(c_str,"efg")! = 0){ jclass err_clz = (*env)->FindClass(env, "java/lang/IllegalArgumentException"); (*env)->ThrowNew(env, err_clz, "key value is invalid!" ); }}Copy the code
The test code is as follows:
public static void main(String[] args) { JniTest test = new JniTest(); try { test.testException(); System.out.println("JNI manually threw an exception, Java will not continue, this sentence will not be printed \n"); } catch (Exception e) {system.out.println (" + LLDB message () + "\n"); } system.out.println (" Program continues, this sentence will be printed \n"); }Copy the code
### Exception handling summary
- JNI throws an exception of the Error type, which Java can catch through Throwable or Error. After catching an exception, Java code can continue to execute. At the C layer, ExceptionClear is allowed to ensure that the Java code in the try continues to execute, and it is best to provide a remedy to ensure that the JNI layer code continues to run normally.
- Exceptions thrown manually by the user through ThrowNew can also be caught in the Java layer.
#### digression — Types of exceptions
Throwable: There are two important subclasses: Exception and Error, both of which are important Java Exception handling subclasses, each containing a large number of subclasses.
Error: An Error that the program cannot handle, indicating a serious problem in running the application. Most errors have nothing to do with what the code writer is doing, and instead represent problems with the JVM (Java Virtual Machine) while the code is running. For example, a Java Virtual Machine run error, an OutOfMemoryError occurs when the JVM no longer has the memory resources it needs to continue with the operation. When these exceptions occur, the Java Virtual Machine (JVM) typically selects thread termination. These errors indicate that the fault occurs on the VM itself or when the VM tries to execute an application, such as a Java Virtual Machine running error or a NoClassDefFoundError. These errors are not detectable because they are outside the control and processing capabilities of the application, and most of them are not allowed to occur while the program is running. Even if an error does occur, a properly designed application should not, by nature, attempt to handle the exception it raises. In Java, errors are described by subclasses of Error.
Exception: An Exception that can be handled by the program itself. The Exception class has an important subclass, RuntimeException. The RuntimeException class and its subclasses represent errors thrown by “common JVM operations.” If, for example, try to use null object reference, dividing by zero or an array, respectively caused a runtime exception (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException.
Note: The difference between exceptions and errors: exceptions can be handled by the program itself, and errors cannot be handled.
Generally, Java exceptions (including Exception and Error) are classified as both checked exceptions (Unchecked exceptions) and unchecked exceptions (unchecked exceptions). Traceable exceptions (exceptions required by the compiler to be handled) : Exceptions that are easy to occur during the running of the correct program. Although a traceable exception is an exception, it can be expected to some extent, and once it occurs, it must be handled in some way.
Except for RuntimeException and its subclasses, all Exception classes and their subclasses are traceable exceptions. This type of exception is checked by the Java compiler. That is, when such an exception is possible in a program, it is either caught with a try-catch statement or thrown with a throws clause declaration, or the compilation fails.
Uncheckable exceptions (exceptions that the compiler does not mandate): Includes runtime exceptions (runtimeExceptions and their subclasses) and errors.
Exception there are two broad categories of runtime and non-runtime exceptions (compile exceptions). Your program should handle these exceptions as much as possible.
Runtime exception: Are RuntimeException class and its subclasses abnormalities, such as NullPointerException (null pointer exception), IndexOutOfBoundsException anomaly) (subscript bounds, etc., these exceptions are not checked exception, in the program can choose to capture processing, also can not handle. These exceptions are usually caused by program logic errors, and programs should logically avoid them as much as possible.
- The characteristic of a runtime exception is that the Java compiler does not check for it. That is, when such an exception may occur in a program, it will be compiled even if it is not caught with a try-catch statement or thrown with a throws clause declaration.
- Non-runtime exceptions (compiled exceptions) : Exceptions other than RuntimeException are of type to the Exception class and its subclasses. An exception that must be handled syntactically. If not handled, the program will fail to compile. For example, IOException, SQLException and user-defined Exception exceptions are not defined.
If you feel that my words are helpful to you, welcome to pay attention to my public number:
My group welcomes everyone to come in and discuss all kinds of technical and non-technical topics. If you are interested, please add my wechat huannan88 and I will take you into our group.