【问题标题】:Does JNI Throw break the method execution?JNI Throw 是否会中断方法执行?
【发布时间】:2020-02-10 06:32:56
【问题描述】:

当我调用env->ThrowNew(clazz, "...")时,C++/C方法的后续执行会停止还是我必须自己停止?

// This is the method which checks if a class can be loaded.

static inline jclass _check_find_class(JNIEnv* env, char* name) {
    jclass clazz = env->FindClass(name);

    if (clazz == NULL) {
        env->ThrowNew(env->FindClass("java/lang/NoClassDefFoundError"), message);
    }

    return clazz;
}

// This method is called in other functions like

jclass load_main_class(JNIEnv* env) {
    auto clazz = _check_find_class(env, "class/which/cannot/be/loaded");

    do_stuff(env, clazz);

    return clazz;
}

当我调用load_main_class 方法时会发生什么,它无法找到类并调用ThrowNew 方法?

【问题讨论】:

    标签: java c++ java-native-interface


    【解决方案1】:

    JNI 异常 does not immediately disrupt the native method execution。但是如果你没有正确处理这个异常,那么任何 JNI 函数调用(除了极少数被显式清除的函数调用)都会崩溃。

    【讨论】:

      【解决方案2】:

      当我调用load_main_class 方法时会发生什么,不是 能找到类并调用ThrowNew方法吗?

      在您的特定情况下,在 env->FindClass(name) 返回 NULL 之后立即挂起的 NoClassDefFoundError 将被您的手动抛出异常 env->ThrowNew(env->FindClass("java/lang/NoClassDefFoundError"), message) 覆盖,该异常将在控制权转移回 Java 代码时抛出。

      您所描述的是在 JNI 代码中处理异常的不当方式。您应该使用env->ExceptionOccurred(); 进行检查,然后调用env->ExceptionClear() 以表明异常已得到处理。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-06-16
        • 2010-12-24
        • 1970-01-01
        • 1970-01-01
        • 2021-07-22
        • 1970-01-01
        • 2023-03-25
        相关资源
        最近更新 更多