Exit in COBOL

Here’s an idiomatic COBOL example demonstrating the concept of exiting a program with a specific status code:

       IDENTIFICATION DIVISION.
       PROGRAM-ID. EXIT-EXAMPLE.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-EXIT-CODE PIC 9(4) VALUE 3.
       
       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           DISPLAY "Program starting..."
           
           *> This DISPLAY will be executed
           DISPLAY "About to exit with code " WS-EXIT-CODE
           
           *> Exit the program with the specified code
           STOP RUN RETURNING WS-EXIT-CODE
           
           *> This DISPLAY will never be executed
           DISPLAY "This line will not be reached".
       
       END PROGRAM EXIT-EXAMPLE.

This COBOL program demonstrates how to exit a program with a specific status code. Here’s an explanation of the code:

  1. We define a variable WS-EXIT-CODE in the WORKING-STORAGE SECTION to hold our exit code value (3 in this case).

  2. In the PROCEDURE DIVISION, we use the STOP RUN RETURNING statement to exit the program with the specified exit code.

  3. Any code after the STOP RUN statement will not be executed, similar to the os.Exit() function in the original example.

To compile and run this COBOL program:

  1. Save the code in a file named exit-example.cob.

  2. Compile the program using your COBOL compiler. For example, with GnuCOBOL:

    $ cobc -x exit-example.cob
  3. Run the compiled program:

    $ ./exit-example
    Program starting...
    About to exit with code 3
  4. Check the exit code:

    $ echo $?
    3

Note that the exact method to check the exit code may vary depending on your operating system and shell.

In COBOL, unlike some other languages, there isn’t a direct equivalent to deferred functions or cleanup operations that are guaranteed to run on program exit. The program will simply terminate when it reaches the STOP RUN statement.

This example shows how COBOL handles program termination and exit codes, which is conceptually similar to the original example, although the syntax and specifics differ due to the nature of COBOL as a language.