Error handling: USE and DECLARATIVES

FILE STATUS

Every file can carry a FILE STATUS variable, two characters filled by each I/O verb. 00 means success, 10 means end of file, and 35 means the file is missing:

SELECT EMPLOYEE-FILE ASSIGN TO "emp.dat" FILE STATUS IS WS-STATUS. 01 WS-STATUS PIC XX.

DECLARATIVES

DECLARATIVES opens a special part of PROCEDURE DIVISION where USE procedures live. A USE AFTER EXCEPTION paragraph runs automatically whenever a file error occurs:

DECLARATIVES. ERROR-SECTION SECTION. USE AFTER EXCEPTION PROCEDURE ON EMPLOYEE-FILE. DISPLAY "File error: " WS-STATUS. END DECLARATIVES.

INVALID KEY

For indexed files, INVALID KEY runs when a READ, WRITE, or DELETE fails on the key. Scope terminators (END-READ, END-WRITE) keep the error path attached to its verb:

READ EMPLOYEE-FILE INVALID KEY DISPLAY "Missing key" NOT INVALID KEY PERFORM PROCESS-ROW END-READ.

The code on this page was run with GnuCOBOL 3.2.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev