Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Implementing Native Methods


Throwing Exceptions from Within a Native Method

You can use the SignalError() function to throw a Java exception from within a native method. This page shows you how.

Let's go back to the NativeExample class that was first introduced in Calling Java Methods from a Native Method(in the Using the Java Native Interface (JNI) trail).

Like other methods that throw exceptions, a native method must declare the exceptions that it can throw in its throws clause. The native method called quote() in the NativeExample class throws an IllegalArgumentException:

native static String quote(int index) throws IllegalArgumentException;
The implementation for the NativeExample class's quote() method uses SignalError() to throw the IllegalArgumentException:
struct Hjava_lang_String *
NativeExample_quote(struct HNativeExample *unused, long index)
{
    char *quotation;

    if (index < 1 || index > 3) {
        SignalError(0, "java/lang/IllegalArgumentException", 0);
        return NULL;
    }

    quotation = quotes[index - 1];
    return makeJavaString(quotation, strlen(quotation));
}
The first argument to SignalError() is the execution environment. You will typically pass in 0 to indicate the current environment.

The second argument is the complete name of the exception to throw. Instead of using periods ('.') to delineate the package and class names in the fully qualified exception name, you use slashes ('/'). The third argument is a string containing a detail message. This message is the same one that you would pass to the Exception constructor if you were to create the exception in Java.


Previous | Next | Trail Map | Integrating Native Methods into Java Programs | Implementing Native Methods