JNI - exception.toString()

June 17th, 2008

Sometimes JNI works. And then it fails.

I am still working on one of the bugs but I found a code to print out the exception (ex.toString() equivalent) in c:

 if (env->ExceptionCheck()) {
  jthrowable e = env->ExceptionOccurred();

  char buf[1024];  memset(buf, 0, 1024);

  // have to clear the exception before JNI will work again.
  env->ExceptionClear();

  jclass eclass = env->GetObjectClass(e);

  jmethodID  mid = env->GetMethodID(eclass, "toString",
                                       "()Ljava/lang/String;");

  jstring jErrorMsg = (jstring) env->CallObjectMethod(e, mid);
  const char* cErrorMsg = env->GetStringUTFChars(jErrorMsg, NULL);
  strcpy(buf, cErrorMsg);
  env->ReleaseStringUTFChars(jErrorMsg, cErrorMsg);
  printf("error: %s\n", buf);
}

[Update]
Of course, I found out the reason why code failed at GetMethodID is because… the jar file didn’t have that particular method. Rather, I must have skipped the notice that signature/return value changed to an array. Waiting for new jar now…

Tags: ,

Leave a Reply