3. Embedded SQL for COBOL : The SQL Communications Area : Error Handling Using the SQLCA : Explicit Error Handling
 
Share this page                  
Explicit Error Handling
Programs can also handle errors by inspecting values in the SQLCA structure at various points. For additional information, see the SQL Reference Guide.
The following example is functionally the same as the previous example, except that the error handling is hard-coded in COBOL statements.
Example: Explicit error handling
DATA DIVISION.
WORKING-STORAGE SECTION.
EXEC SQL INCLUDE SQLCA END-EXEC.
EXEC SQL BEGIN DECLARE SECTION END-EXEC.
  01 E-REC.
     02 ENO        PIC S9(8) USAGE DISPLAY.
     02 ENAME      PIC X(20).
     02 AGE        PIC S9(4) USAGE DISPLAY.
  01 NOT-FOUND     PIC S9(4) USAGE COMP VALUE 100.
  01 REASON        PIC X(14).
  01 ERRMSG        PIC X(100).
EXEC SQL END DECLARE SECTION END-EXEC.
PROCEDURE DIVISION.
BEGIN.
    EXEC SQL DECLARE empcsr CURSOR FOR
        SELECT eno, ename, age
        FROM employee
        END-EXEC.
* Exit if database cannot be opened
    EXEC SQL CONNECT personnel END-EXEC.
    IF SQLCODE < 0 THEN
        DISPLAY "Cannot access database"
        STOP RUN.
* Error if cannot open cursor
    EXEC SQL OPEN empcsr END-EXEC.
    IF SQLCODE < 0 THEN
        MOVE "OPEN ""empcsr""" TO REASON
        PERFORM CLEAN-UP.
    DISPLAY "Some values from the ""employee"" table".
* The last statement was an OPEN, so we know that the
* value of SQLCODE cannot be SQLERROR or NOTFOUND.
    PERFORM UNTIL SQLCODE NOT = 0
        EXEC SQL FETCH empcsr
               INTO :ENO, :ENAME, :AGE
               END-EXEC.
        IF SQLCODE < 0 THEN
            MOVE "FETCH ""empcsr""" TO REASON
            PERFORM CLEAN-UP
* Do not print the last values twice
        ELSE
            IF SQLCODE NOT = NOT-FOUND THEN
                DISPLAY E-REC
            END-IF
        END-IF
    END-PERFORM.
    EXEC SQL CLOSE empcsr END-EXEC.
    EXEC SQL DISCONNECT END-EXEC.
    STOP RUN.
  CLEAN-UP.
* Error handling paragraph
    DISPLAY "Aborting because of error in " REASON.
    EXEC SQL INQUIRE_SQL(:ERRMSG = ERRORTEXT) END-EXEC.
    DISPLAY ERRMSG.
    EXEC SQL DISCONNECT END-EXEC.
    STOP RUN.