The following short COBOL program throws an exception using a JNI function.
identification division. program-id. "except". special-names. ********************************************** * The call convention used for JNI calls needs * to be defined here. For Win32 systems, it is * 74 (which corresponds to the stdcall calling * convention). ********************************************** $if UNIX defined call-convention 0 is javaapi. $else call-convention 74 is javaapi. $end local-storage section. copy "javatypes.cpy". 01 JavaException pointer. 01 ExceptionClass pointer. linkage section. 01 JEnv pointer. 01 jobject pointer. 01 lnk-JNINativeInterface JNINativeInterface. * The first parameter (JEnv) is a pointer to the JNI * function table. It must be passed (by reference) as * the first parameter on all JNI function calls. procedure division using by reference JEnv. * Map the pointer passed in JEnv to the * JNINativeInterface structure so that we * can call JNI functions. set address of lnk-JNINativeInterface to JEnv * Get a reference to the exception class call javaapi FindClass using by reference JEnv by reference z"java/lang/IllegalArgumentException" returning ExceptionClass end-call * Unable to find the exception class, so simply exit if ExceptionClass = NULL exit program end-if * Throw the new exception call javaapi ThrowNew using by reference JEnv by value ExceptionClass by reference z"Thrown from COBOL code" end-call exit program .
This is the Java program which calls it:
import com.microfocus.cobol.*; class testexcept { public static void main(String argv[]) throws Exception { try { /* Last parameter is true for passing in JNIEnv... */ RuntimeSystem.cobcall(null,"throwex",null,null,true); } catch(Exception e) { System.out.println( "PASS - exception caught ("+ e + ")"); } } }