Throw an Exception (from JNI code)Tag(s): JNI


Define the following prototype in the header file
JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide
  (JNIEnv *, jobject, jdouble, jdouble);
the JNI function
JNIEXPORT jdouble JNICALL Java_JavaHowTo_divide
  (JNIEnv *env, jobject obj, jdouble d1, jdouble d2) {
    if (d2 == 0.0) {
        jclass Exception = env->FindClass("java/lang/Exception");
        env->ThrowNew(Exception,"Can't divide by zero.");
    }
    return d1/d2;
    }
The Java JNI wrapper would be
class JavaHowTo {
  public native double divide(double d1, double d2);
  static {
    System.loadLibrary("javahowto"); 
  }
}
And finally, to use it
public class JNIJavaHowTo {
  public static void main(String[] args) {
    JavaHowTo jht = new JavaHowTo();
    System.out.println("division 1 : " + jht.divide(9.0, 3.0));
    System.out.println("division 2 : " + jht.divide(9.0, 0.0));
    }
}

blog comments powered by Disqus