Introduction to Using the Raw Native Interface
 
 

Java & Native Code    PreviousRNINext
Introduction to Using the Raw Native Interface     Previous RNI Next

 


Throwing Java Exceptions from Native Code

To throw Java exceptions from native code, you can use the SignalError API. This creates a Java exception object that will be thrown upon return from the native code (the normal execution of the native code is not interrupted). This is shown in the following example:

    if (makeJavaString("Hello", 5) == NULL)
    {
        SignalError(NULL, "java/lang/OutOfMemoryError", "Failed to create string.");
        return;
    }

The first parameter is the environment (which should always be NULL), the second is the class name of the Java exception you want to throw (this must be a Java Throwable or a subclass of Throwable), and the third is the "detail string" (which can be NULL).

If you call into Java using something like execute_java_dynamic_method, it's possible that an uncaught exception was thrown during its execution. To test for this case, you can use the exceptionOccured API. It takes NULL as its only parameter and returns TRUE if an exception was thrown and FALSE otherwise. You can produce a stack trace of the exception (to the System.err PrintStream) using exceptionDescribe. You can destroy the exception using exceptionClear.

For example:

    // Make sure there isn't already a pending exception.
    exceptionClear(NULL);

    // Call method.
    execute_java_dynamic_method(...);

    // Check if something bad happened.
    if (exceptionOccurred(NULL))
    {
        // Make sure people are aware of the problem.
        exceptionDescribe(NULL);

        // Stop the exception from being propergated. 
        exceptionClear(NULL);
    }

Top © 1998 Microsoft Corporation. All rights reserved. Terms of use.