Semyon Tikhonenko
Semyon Tikhonenko

Reputation: 4252

Is C++ destructor called after java exception is thrown from JNI function?

I wonder if ~JniFloatArray of dataArray is called, when com/emcjpn/sleep/SleepAlgorithmBreakException is thrown?

JNIEXPORT jobject JNICALL    Java_com_emcjpn_sleep_SleepAlgorithm_nativePushNewDataAndCalculate(JNIEnv *env, jclass type,
                                                                       jlong ptr, jfloatArray data_) {
        JniFloatArray dataArray(data_, env);
        jfloat *data = dataArray.getData();

        SleepAlgorithm* algorithm = (SleepAlgorithm*)ptr;
        jsize length = dataArray.length();
        SleepAlgorithmResult result = algorithm->pushNewDataAndCalculate(data, data + length);
        if (result.shouldBreak) {
            jclass exception = env->FindClass("com/emcjpn/sleep/SleepAlgorithmBreakException");
            env->ThrowNew(exception, "sleep calculation failed, invalid ecg data");
            return NULL;
        }

        /*Some other code*/
    }

Upvotes: 1

Views: 212

Answers (1)

Yes. It's hard to find in the JNI documentation, but env->ThrowNew doesn't actually throw an exception immediately. Instead it sets things up so that an exception is thrown once you return to Java-land.

This means you must follow ThrowNew with a return of some sort (to get back to Java-land), and that return will cause all the destructors to run.

Upvotes: 3

Related Questions