Learn Java

Throw Exception in Native Function

Implementation

The example can be found in exception. The native function throws an IllegalArgumentException to Java.

ExceptionInNative.java:

public class ExceptionInNative{

    public static native void throwException(String clazz, 
        String info);

    static{
        System.loadLibrary("ThrowException");
    }

    public static void main(String[] args){
        throwException("java/lang/IllegalArgumentException", 
            "This exception is thrown from C code");
    }
}

ExceptionInNative.c:

#include "ExceptionInNative.h"

char* jstringTostring(JNIEnv* env, jstring javaString)
{
   return (*env)->GetStringUTFChars(env, javaString, 0);
}

JNIEXPORT void JNICALL Java_ExceptionInNative_throwException
(JNIEnv * env, jclass class, jstring clazz, jstring info)
{
    char* classExceptionString = jstringTostring(env,clazz);
    char* infoString = jstringTostring(env, info);

     jclass classException = (*env)->FindClass(env, 
             classExceptionString);
    if (classException != NULL) {
        (*env)->ThrowNew(env, classException, infoString); //2
    }
    (*env)->DeleteLocalRef(env, classException); //3
    (*env)->ReleaseStringUTFChars(env, clazz, classExceptionString);
    (*env)->ReleaseStringUTFChars(env, info, infoString);
}

Explains

JNI Methods:

  • ReleaseStringUTFChars, ReleaseStringChars:

    release memory on C string

  • FindClass: Find class by its name
  • ThrowNew: Throw the exception using the class reference we got before and the message for the exception
  • DeleteLocalRef: Delete local reference

Result

export LD_LIBRARY_PATH=.
java ExceptionInNative
Exception in thread "main" java.lang.IllegalArgumentException: 
    This exception is thrown from C code
        at ExceptionInNative.throwException(Native Method)
        at ExceptionInNative.main(ExceptionInNative.java:10)
make: *** [test] Error 1