I tried your approach and it worked for me. A few things: I use the C ++ interface (although this should not change), and I use the update version for Java 6 version 10, x64 on Ubuntu 8.04. Perhaps the version of Java you are using and / or the platform will matter.
#include <cstdio> #include <jni.h> int main(int argc, char** argv) { if (argc != 3) { std::fprintf(stderr, "usage: %s class message\n", argv[0]); return 1; } JavaVM* jvm; void* penv; JavaVMInitArgs args = {JNI_VERSION_1_6}; if (jint res = JNI_CreateJavaVM(&jvm, &penv, &args)) { std::fprintf(stderr, "Can create JVM: %d\n", res); return -res; } JNIEnv* env(static_cast<JNIEnv*>(penv)); jint vers(env->GetVersion()); std::printf("JNI version %d.%d\n", vers >> 16, vers & 0xffff); env->ThrowNew(env->FindClass(argv[1]), argv[2]); jthrowable exc(env->ExceptionOccurred()); std::printf("Exception: %p\n", exc); if (exc) { jclass exccls(env->GetObjectClass(exc)); jclass clscls(env->FindClass("java/lang/Class")); jmethodID getName(env->GetMethodID(clscls, "getName", "()Ljava/lang/String;")); jstring name(static_cast<jstring>(env->CallObjectMethod(exccls, getName))); char const* utfName(env->GetStringUTFChars(name, 0)); jmethodID getMessage(env->GetMethodID(exccls, "getMessage", "()Ljava/lang/String;")); jstring message(static_cast<jstring>(env->CallObjectMethod(exc, getMessage))); char const* utfMessage(env->GetStringUTFChars(message, 0)); std::printf("Exception: %s: %s\n", utfName, utfMessage); env->ReleaseStringUTFChars(message, utfMessage); env->ReleaseStringUTFChars(name, utfName); } return -jvm->DestroyJavaVM(); }
I used jnitest java/lang/InternalError 'Hello, world!' for my testing; Feel free to use different types of exceptions!
Chris jester-young
source share