Best way to throw exceptions in JNI code?

前端 未结 4 1561
终归单人心
终归单人心 2020-12-02 10:09

I\'d like a consistent and simple way to throw exceptions in JNI code; something that handles chained exceptions (implicitly from the env->ExceptionOccurred method, or expli

4条回答
  •  渐次进展
    2020-12-02 10:31

    I will put a more complete and general answer for who need a little bit more explanations like I need before.

    First is nice to set your method with a Throw Exception so the IDE will ask for try/catch.

    public native int func(Param1, Param2, Param3) throws IOException;
    

    I decide for IOException over Exception because of this.

    JNIEXPORT int JNICALL Java_YourClass_func
    (int Param1, int Param2, int Param3) {
        if (Param3 == 0) { //something wrong
            jclass Exception = env->FindClass("java/lang/Exception");
            env->ThrowNew(Exception, "Can't divide by zero."); // Error Message
        }
        return (Param1+Param2)/Param3;
    }
    

提交回复
热议问题