Friday, April 19, 2013

jni jnienv ThrowNew example c c++ java

ThrowNew

jint ThrowNew(JNIEnv *env, jclass clazz, const char *message);

Constructs an exception object from the specified class with the message specified by message and causes that exception to be thrown.

LINKAGE:
Index 14 in the JNIEnv interface function table.
PARAMETERS of ThrowNew

env: the JNI interface pointer.

clazz: a subclass of java.lang.Throwable.

message: the message used to construct the java.lang.Throwable object. The string is encoded in modified UTF-8.

RETURNS:

Returns 0 on success; a negative value on failure.

THROWS:

the newly constructed java.lang.Throwable object.
Example 
jint
throwNoClassDefError( JNIEnv *env, char *message )

{
jclass exClass;
char *className = "java/lang/NoClassDefFoundError" ;

exClass = (*env)->FindClass( env, className );
if ( exClass == NULL )
{
return throwNoClassDefError( env, className );
}

return (*env)->ThrowNew( env, exClass, message );
}

jint
throwNoSuchMethodError(

JNIEnv *env, char *className, char *methodName, char *signature )
{
jclass exClass;
char *exClassName = "java/lang/NoSuchMethodError" ;
LPTSTR msgBuf;
jint retCode;
size_t nMallocSize;

exClass = (*env)->FindClass( env, exClassName );
if ( exClass == NULL )
{
return throwNoClassDefError( env, exClassName );
}

nMallocSize = strlen(className) 
+ strlen(methodName)
+ strlen(signature) + 8;

msgBuf = malloc( nMallocSize );
if ( msgBuf == NULL )
{
return throwOutOfMemoryError
( env, "throwNoSuchMethodError: allocating msgBuf" );
}
memset( msgBuf, 0, nMallocSize );

strcpy( msgBuf, className );
strcat( msgBuf, "." );
strcat( msgBuf, methodName );
strcat( msgBuf, "." );
strcat( msgBuf, signature );

retCode = (*env)->ThrowNew( env, exClass, msgBuf );
free ( msgBuf );
return retCode;
}

jint
throwNoSuchFieldError( JNIEnv *env, char *message )

{
jclass exClass;
char *className = "java/lang/NoSuchFieldError" ;

exClass = (*env)->FindClass( env, className );
if ( exClass == NULL )
{
return throwNoClassDefError( env, className );
}

return (*env)->ThrowNew( env, exClass, message );
}

jint
throwOutOfMemoryError( JNIEnv *env, char *message )

{
jclass exClass;
char *className = "java/lang/OutOfMemoryError" ;

exClass = (*env)->FindClass( env, className );
if ( exClass == NULL )
{
return throwNoClassDefError( env, className );
}

return (*env)->ThrowNew( env, exClass, message );