Panic in COBOL
Our program demonstrates how to handle unexpected errors or conditions. In COBOL, we use the STOP RUN
statement to abruptly terminate the program, which is similar to the concept of panic in other languages.
IDENTIFICATION DIVISION.
PROGRAM-ID. PANIC-EXAMPLE.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT TEMP-FILE ASSIGN TO "/tmp/file"
ORGANIZATION IS LINE SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD TEMP-FILE.
01 TEMP-RECORD PIC X(80).
WORKING-STORAGE SECTION.
01 WS-ERROR-MESSAGE PIC X(50).
PROCEDURE DIVISION.
MAIN-PROCEDURE.
DISPLAY "Starting the program"
* This is equivalent to the first panic in the original example
MOVE "a problem" TO WS-ERROR-MESSAGE
PERFORM HANDLE-ERROR
* This part demonstrates file handling error
OPEN OUTPUT TEMP-FILE
IF NOT FILE-STATUS = "00"
MOVE "Error creating file" TO WS-ERROR-MESSAGE
PERFORM HANDLE-ERROR
END-IF
CLOSE TEMP-FILE
STOP RUN.
HANDLE-ERROR.
DISPLAY "ERROR: " WS-ERROR-MESSAGE
STOP RUN.
Running this program will cause it to terminate abruptly, print an error message, and exit with a non-zero status.
When the first HANDLE-ERROR
is performed, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first PERFORM HANDLE-ERROR
.
$ cobc -x panic-example.cob
$ ./panic-example
Starting the program
ERROR: a problem
Note that in COBOL, it’s common to use condition handling and status codes for error management. The STOP RUN
statement is used here to simulate a panic-like behavior, but in real COBOL programs, more structured error handling methods are typically employed.