Example 5 - COBOL Exception Reporting When Calling Java Static Methods

This example demonstrates how you can build in some user-defined exception processing into your COBOL programs that call Java static methods.
In this simple example, an exception is deliberately encountered when the size of the Java array that is retrieved by the COBOL program does not match the size of the corresponding table. A simple message is generated in this instance, but you could use the ON EXCEPTION phrase to perform more complex processing from within COBOL, if required.
Important: For UNIX platforms, ensure that the current working folder and the folder containing libjvm.so is available on the LD_LIBRARY_PATH (or LIBPATH on AIX) environment variable.
  1. Create the following Java file (Demo5.java)
    public class Demo5 {
    
        /* Array size error */
        public static int[] static5()
        {
            int i[] = {1,2,3,4,5,6};
            return i;
        }
    }
  2. Ensure that the current working folder is on the CLASSPATH (UNIX/Linux platforms only)
  3. Compile Demo5.java:
    javac Demo5.java

    This produces a Demo5.class file in the current folder.

  4. In the same folder, create the following COBOL file (demo5.cbl):
           program-id. "demo5".
           working-storage section.
            01 table5.
             03 num5 pic x(4) comp-5 occurs 5.
    
           linkage section.
           procedure division.
    
          *> out of bounds Java will return an array larger than the COBOL size
               call "java.Demo5.static5" returning table5
               on exception
                   display "Exception occurred due to array mismatch"
               not on exception
                   display "call successful"
               end-call.
           goback.
  5. Compile and link the COBOL file:

    Windows:

    cobol demo5.cbl; 
    cbllink demo5.obj

    UNIX:

    cob -x demo5.cbl  

    This produces the final COBOL executable file, demo1.exe (Windows) or demo1 (UNIX).

  6. Run the executable file:

    Windows:

    demo5.exe

    UNIX:

    ./demo5

    The program should encounter an exception due a mismatch between table5 in the COBOL program and the i array in the static5 method, and output the following:

    Exception occurred due to array mismatch

    To process the not on exception phrase, change one of these elements to match the other, and then recompile.