Custom Errors in COBOL
Our first example demonstrates how to create custom errors in COBOL. While COBOL doesn’t have a built-in error handling mechanism like Go’s error interface, we can simulate a similar concept using custom structures and procedures.
IDENTIFICATION DIVISION.
PROGRAM-ID. CUSTOM-ERRORS.
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-ARG-ERROR.
05 ARG PIC 9(5).
05 MESSAGE PIC X(50).
01 WS-RESULT PIC S9(5).
01 WS-ERR PIC X.
88 ERR-OCCURRED VALUE 'Y'.
88 NO-ERR VALUE 'N'.
PROCEDURE DIVISION.
MAIN-PROCEDURE.
PERFORM F-PROCEDURE
IF ERR-OCCURRED
DISPLAY "ARG: " ARG
DISPLAY "MESSAGE: " MESSAGE
ELSE
DISPLAY "No error occurred"
END-IF
STOP RUN.
F-PROCEDURE.
MOVE 42 TO ARG
IF ARG = 42
MOVE -1 TO WS-RESULT
MOVE "Y" TO WS-ERR
MOVE "can't work with it" TO MESSAGE
ELSE
ADD 3 TO ARG GIVING WS-RESULT
MOVE "N" TO WS-ERR
END-IF.In this COBOL program, we’ve created a custom structure WS-ARG-ERROR to represent our error. It contains an ARG field for the argument and a MESSAGE field for the error message.
The F-PROCEDURE simulates the function f from the Go example. It checks if the argument is 42, and if so, it sets an error condition and populates the WS-ARG-ERROR structure.
In the MAIN-PROCEDURE, we call F-PROCEDURE and then check if an error occurred. If it did, we display the error information.
To run this program, you would typically compile it and then execute the resulting binary. The exact commands depend on your COBOL compiler, but it might look something like this:
$ cobc -x custom-errors.cob
$ ./custom-errors
ARG: 00042
MESSAGE: can't work with itThis example demonstrates how we can implement a form of custom error handling in COBOL, even though the language doesn’t have built-in support for this concept in the same way Go does.