Java Reference
In-Depth Information
Native code you write can also raise Java exceptions - either standard excep-
tions like java.lang.IOException or custom exceptions of your own design.
Of course the Java definition of the custom exception must already exist on the
Java side - i.e. if you want to throw MyCustomException from native code,
there must already exist a Java MyCustomException class somewhere in the
CLASSPATH on the Java side.
There are two ways to handle exceptions in native code. In the examples shown
so far, after detecting an error code return, we have chosen to return immediately to
the calling Java method. This return causes the exception to be thrown and handled
on the Java side like any Java exception. Note that the exception isn't really thrown
to Java until the native code returns. The exception has been raised on the native
side by JNI, but it is said to be pending until the native code returns to the Java side.
Once the native code returns, then the JNI system arranges for the pending excep-
tion to be thrown on the Java side. In that way, returning immediately to Java when
we detect the presence of an error code allows the exception to be handled on the
Java side.
The second way to handle exceptions in native code is to explicitly check for
and handle a pending exception within the native code itself. We describe this
technique next.
We emphasize that it is extremely important to handle all exceptions by one
of these two methods. Continuing to make additional JNI function calls after
an exception has been raised can lead to unpredictable results. In fact, the only
JNI functions that are safe to call after an exception has been raised are the
four special exception handling functions, ExceptionOccurred() , Excep-
tionCheck() , ExceptionClear() , and ExceptionDescribe() . The
main JNI exception handling function is ExceptionOccurred() ,which
checks to see if any exception is pending and returns a jthrowable if so.
It is used as follows:
// ...
// some code that might raise an exception
jthrowable jth = jenv- > ExceptionOccurred ();
if (jth) {
jenv- > ExceptionClear ();
// handle the exception...
}
The ExceptionOccurred() function returns NULL if there is no exception.
If a jthrowable is returned, then there is a pending exception of some kind.
If you plan to handle the exception within native code, the JNI system should be
told about your plans by calling the ExceptionClear() function. Otherwise
the exception is left pending and will be thrown on the Java side when the native
code eventually returns to Java. The ExceptionDescribe() function is used
to print a debugging message about the pending exception.
Search WWH ::




Custom Search