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.
  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. Compile Demo5.java:
    javac Demo5.java

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

  3. 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.
  4. Compile and link the COBOL file:
    cobol demo5.cbl; 
    cbllink demo5.obj

    This produces the final COBOL executable file, demo1.exe.

  5. Run the executable file:
    demo5.exe

    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.