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 the Calling Java Methods from a Native Method(in the Integrating Native Methods into Java Programs trail)section on the page titled Using a Java Object in a Native Method.

Like other methods that throw exceptions, a native method must declare the exceptions that it can throw in its throws clause. The native method, 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 exception:
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. The third argument is [PENDING: what?].


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