Implementing Native Methods |
You can use theSignalError()
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.
Like other methods that throw exceptions, a native method must declare the exceptions that it can throw in its
throws
clause. The native method calledquote()
in the NativeExample class throws an IllegalArgumentException:The implementation for the NativeExample class'snative static String quote(int index) throws IllegalArgumentException;quote()
method usesSignalError()
to throw the IllegalArgumentException:The first argument tostruct 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)); }SignalError()
is the execution environment. You will typically pass in0
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.
Implementing Native Methods |