Error Handling


The code in the programs may cause runtime errors or the program to abend based on the different possible inputs. Error handling is a mechanism used to handle the possible runtime errors by notifying the user with a message or routing the program flow to skip the program abend. The error handling code can take actions such as handling the situation, issuing a message, or stopping the program execution.

Error handling is necessary in COBOL, just as in any programming language. COBOL has specific categories to handle the error conditions -

  • Handling errors in STRING and UNSTRING operations.
  • Handling errors in Arithmetic operations.
  • Handling errors in File operations.
  • Handling errors in CALL statements.

Handling errors in STRING and UNSTRING operations -


During the string operations, the result string length may fall outside the size of the receiving variable. This causes the result string truncation and does not notify the user. The ON OVERFLOW phase is used to handle the overflow condition and notify the end user about it.

The possible error handles are -

Handling errors in arithmetic operations -


The arithmetic operation (ADD, SUBTRACT, MULTIPLY, DIVIDE, or COMPUTE) might produce a larger value than the target variable size or have tried dividing by zero at runtime. The program execution fails because of the above error. ON SIZE ERROR phrase can handle the scenarios if they are coded with arithmetic statements.

The ON SIZE ERROR handles the following cases -

  • Fixed-point overflow.
  • Division by zero.
  • Zero raised to zero power.
  • Zero raised to a negative number.
  • The negative number raised to a fractional power.

The possible error handlings are -

Handling errors in file operations -


COBOL does not automatically take corrective action when file input or output operation fails. The user should choose whether the program will continue or fail when an input or output error.

The techniques below is used for handling specific input or output conditions or errors -

  • FILE STATUS clause and file status key.
  • End-of-file condition (AT END Phrase) for sequential files.
  • INVALID KEY Phrase for indexed and relative files.

The possible error handlings are -

Handling errors in CALL statement -


The application program might abend when -

  • A program dynamically calls a subprogram, the load module of the subprogram is unavailable.
  • The CALL statement does not have an ON EXCEPTION phrase.

ON EXCEPTION phrase handles the above errors, and it also handles the errors that occur when the subprogram is unavailable on its initial load. It can't handle the error if the called program is loaded but fails for any other reason.

The possible error handlings are -

ScenarioStatement
For error handling flowCALL ON EXCEPTION
For success flowCALL NOT ON EXCEPTION