Handling Errors in File Operations

Handling Errors in File Operations

As we advance in our journey of learning COBOL file handling, it's essential to address the practical aspects of working with files, such as dealing with errors. In previous lessons, we've learned how to create, read, write, and append records to both sequential and indexed files. In this lesson, we'll explore how to handle errors that can arise during file operations, ensuring that your programs are robust and reliable.

What You'll Learn

In this lesson, you'll learn how to implement error handling in COBOL file operations. Mistakes can happen: a file might not exist, a read operation might fail, or issues could occur while writing to a file. We'll focus on checking file statuses and responding to errors gracefully.

Let's look at an example:

IDENTIFICATION DIVISION.
PROGRAM-ID. ErrorHandlingDemo.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT InputFile ASSIGN TO 'non-existing-file.dat'
    ORGANIZATION IS SEQUENTIAL
    FILE STATUS IS WS-FILE-STATUS.
DATA DIVISION.
FILE SECTION.
FD  InputFile.
01  InputRecord.
    05 Customer-Name PIC X(30).
    05 Account-Number PIC 9(10).
    05 Account-Balance PIC 9(8)V99.
WORKING-STORAGE SECTION.
01 WS-FILE-STATUS PIC XX VALUE '00'.
PROCEDURE DIVISION.
    OPEN INPUT InputFile
        IF WS-FILE-STATUS NOT = '00'
            DISPLAY "Error opening file: " WS-FILE-STATUS
            STOP RUN.
    CLOSE InputFile.
    STOP RUN.

In this snippet, we attempt to open a non-existing file and check the file status to handle the error appropriately.

Let's analyze the essential components of the code:

  • We first define the file structure as before, with the FILE-CONTROL and FILE SECTION sections.
  • We introduce a new variable, WS-FILE-STATUS, to store the file status, with an initial value of '00'. This variable will hold the status of file operations; if the file doesn't exist, the value will be set to a non-zero value. Note, that this variable is referenced in the FILE STATUS IS clause in the FILE-CONTROL section, which specifies the file status variable.
  • We attempt to open the file using the OPEN INPUT statement and check the file status using the IF condition.
    • If the file status is not equal to '00', we display an error message and stop the program.
    • The file status '00' indicates that the file operation was successful.

Since we do not have the file non-existing-file.dat, the OPEN INPUT operation will fail, and the file status will be set to a non-zero value. We check this status and display an error message if the file opening operation fails.

When you run this program, you should see the following output:

Error opening file: 35
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal