JNI exception capture

1. JNI catches an exception and clears it

java provides a method with exception

	public int getNumBer(){
    
    
        return 4/0; // 异常行
    }
    // 定义一个native方法
 public native int init();

JNI code capture cleanup

extern "C"
JNIEXPORT jint JNICALL
Java_com_xyx_open_MainActivity_init(JNIEnv *env, jobject thiz) {
    
    
    jclass mainActivityClz = env->GetObjectClass(thiz);
    jmethodID getNumber_C = env->GetMethodID(mainActivityClz, "getNumBer", "()I");
    jint result = env->CallIntMethod(thiz, getNumber_C);
    LOGE("开始捕捉异常.........");
    // 捕捉异常
    jthrowable jthrowable1= env->ExceptionOccurred();
    // 如果有异常
    if (jthrowable1){
    
    
        LOGE("出现异常了.........");
        // 清除异常信息
        env->ExceptionClear();
        return  -1 ;
    }
    return  result;
}

2. JNI catches the exception, clears it, and throws it to Java

java code:

	try {
    
    
         init2();
     }catch (IllegalArgumentException e){
    
    
         
         Log.e("zyb", "onCreate: 参数异常...."+e.getMessage() );
     }

public native int init2()throws IllegalArgumentException;


    public int getNumBer(){
    
    
        return 4/0;
    }

c++ code

extern "C"
JNIEXPORT jint JNICALL
Java_com_xyx_open_MainActivity_init2(JNIEnv *env, jobject thiz) {
    
    
    jclass mainActivityClz = env->GetObjectClass(thiz);
    jmethodID getNumber_C = env->GetMethodID(mainActivityClz, "getNumBer", "()I");
    jint result = env->CallIntMethod(thiz, getNumber_C);
    LOGE("开始捕捉异常.........");
    // 捕捉异常
    jthrowable jthrowable1= env->ExceptionOccurred();
    // 如果有异常
    if (jthrowable1){
    
    
        LOGE("出现异常了.........");
        // 清除异常信息
        env->ExceptionClear();
        jclass exception=env->FindClass("java/lang/IllegalArgumentException");
        env->ThrowNew(exception,"参数异常.分母为0了.....");
        return  -1 ;
    }
    return  result;

}

3. JNI catches and throws exception java method

  public native void init3();

    public int getNumBer2(int div){
    
    
        if (div==0) throw new IllegalArgumentException("参数出错误了 ......");
        return 4/div;
    }

c++ code

extern "C"
JNIEXPORT void JNICALL
Java_com_xyx_open_MainActivity_init3(JNIEnv *env, jobject thiz) {
    
    

    jclass mainActivityClz = env->GetObjectClass(thiz);
    jmethodID getNumber_C = env->GetMethodID(mainActivityClz, "getNumBer2", "(I)I");
    jint result = env->CallIntMethod(thiz, getNumber_C,0);
    LOGE("开始捕捉异常.........");
    // 捕捉异常
    jboolean jthrowable1= env->ExceptionCheck();
    // 如果有异常
    if (jthrowable1){
    
    
        LOGE("出现异常了.........");
        // 清除异常信息
        env->ExceptionClear();
    }
    LOGE("程序继续运行.........");

}

Guess you like

Origin blog.csdn.net/baidu_31956557/article/details/127540691