From: Jaydeep Chovatia on
Hi,

I have written an application in which i am calling java method from C+
+ using JNI(Java Native Interface). I would like to handle exceptions
in C++ raised inside JAVA method. I am able to do that successfully. I
also want class name of the exception object in C++ and for that I
have written following code, but line no. 9 retruns null object(pease
see code below).

1 jobject jResponseMailbox = jenv->CallStaticObjectMethod(...);
2 if(jenv->ExceptionCheck() == JNI_TRUE )
3 {
4 jthrowable exceptionObj = jenv->ExceptionOccurred();
5 jclass exceptionClass = jenv->GetObjectClass( exceptionObj );
6
7 jmethodID msgMethodID;
8 const char* localstr = NULL;
9 msgMethodID = jenv->GetMethodID(exceptionClass, "getName",
"()Ljava/lang/String;");
10 if(msgMethodID == NULL) {
11 printf("\ngetName is returning NULL......\n");
12 } else {
13 jstring clsName = (jstring)jenv-
>CallObjectMethod(exceptionClass, msgMethodID, NULL);
14 localstr = jenv->GetStringUTFChars(clsName, NULL);
15 printf("\n\nException class name: %s\n", localstr);
16 }
17 }

Can you please suggest me how to get class name?

Thank you,
Jaydeep
From: Zig on
On Wed, 24 Mar 2010 00:58:00 -0400, Jaydeep Chovatia
<chovatia.jaydeep(a)gmail.com> wrote:

> also want class name of the exception object in C++ and for that I
> have written following code, but line no. 9 retruns null object(pease
> see code below).
>
> 1 jobject jResponseMailbox = jenv->CallStaticObjectMethod(...);
> 2 if(jenv->ExceptionCheck() == JNI_TRUE )
> 3 {
> 4 jthrowable exceptionObj = jenv->ExceptionOccurred();
> 5 jclass exceptionClass = jenv->GetObjectClass( exceptionObj );
> 6
> 7 jmethodID msgMethodID;
> 8 const char* localstr = NULL;
> 9 msgMethodID = jenv->GetMethodID(exceptionClass, "getName",
> "()Ljava/lang/String;");

getName is not a method declared by your exception class - it's declared
by java.lang.Class.

Something like:

jclass classMethodAccess = jenv->FindClass("java/lang/Class");
jmethodID classNameMethodID = jenv->GetMethodID(classMethodAccess,
"getName", "()Ljava/lang/String;");
jstring clsName=(jstring) env->CallObjectMethod(exceptionObj,
classNameMethodID);

Should do the trick (though I haven't tested it yet).

HTH,

-Zig
From: EJP on
I would be very careful about that. You're already in an exception, you
don't want to provoke another one by getting fancy. I would just either
use the built-in JNI functions to print the exception and stack trace or
let it be thrown back to the caller and let him handle it in Java.