Example of Throwing an Exception

Restriction: This applies to native code only.

The following short COBOL program throws an exception using a JNI function.

 identification division.
 program-id.  "except".

* 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.
     call-convention 74 is javaapi.
 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
             returning ExceptionClass
* Unable to find the exception class, so simply exit
     if ExceptionClass = NULL
             exit program
* Throw the new exception
     call javaapi ThrowNew
             using by reference JEnv
                   by value ExceptionClass
                   by reference z"Thrown from COBOL code"
     exit program

This is the Java program which calls it:

import com.microfocus.cobol.*;
class testexcept
  public static void main(String argv[]) throws Exception
       /* Last parameter is true for passing in JNIEnv... */
    catch(Exception e)
                  "PASS - exception caught ("+ e + ")");