Java Reference
In-Depth Information
If you want only to check on the existence of a pending exception without
creating a local reference to the
jthrowable
exception object, the
Excep-
tionCheck()
function may be used. It returns
JNI
-
TRUE
if an exception is
pending and
JNI
-
FALSE
if not.
Often, after detecting an exception in native code, what you really want to do
is handle the exception in Java code by throwing your own exception, perhaps
with a bit more description about what went wrong. Or sometimes, by careful
coding, you might detect an error condition in your own native code even before
calling a JNI function that would raise an exception. In these cases, you need to
throw your own exceptions back to Java, the subject of the next section.
22.10.2 Throwing exceptions in native code
Suppose we determine, either by detecting an exception thrown by a JNI function
we called, or by our own error checking of the arguments received from the Java
side, that some of the arguments are invalid. In that case we might want to throw
a
java.lang.IllegalArgumentException
back to the Java code.
On the Java side, throwing an
IllegalArgumentException
is simple:
throw new IllegalArgumentException (
"
...
"
);
Throwing an exception on the native side is only slightly more complicated. The
ThrowNew()
function is used to throw an exception from native code to Java.
This function takes a
jclass
specifying the exception class to be thrown and
a string message to include with the exception. Therefore we must first find the
jclass
representing the
IllegalArgumentException
.Wecan find that
jclass
using
FindClass()
, just like finding any other class:
jclass iae
-
cls
=
jenv-
>
FindClass (
"
java/lang/IllegalArgumentException
"
);
if (iae
-
cls
==
NULL)
// just give up if we can't even find the
// IllegalArgumentException class
return;
With the desired exception
jclass
in hand, we throw it as follows:
jenv-
>
ThrowNew (iae
-
cls,
"
illegal argument detected in native code
"
);
The second parameter to
ThrowNew()
is the message to be used when con-
structing the
java.lang.Exception
or
java.lang.Throwable
object.
On the Java side, J2SE 1.4 added the ability to chain exceptions by specifying a
Throwable
as a
cause
parameter to the
Exception
and
Throwable
construc-
tors. As of this writing, there is no simple way to provide a
Throwable
cause
Search WWH ::
Custom Search