One simple method to catch errors and warnings is to set a specific action to be executed whenever a particular condition occurs. In general:
EXEC SQL WHENEVER condition action END-EXEC.
condition can be one of the following:
The specified action is called whenever an error occurs during the execution of an SQL statement.
The specified action is called whenever a warning occurs during the execution of an SQL statement.
The specified action is called whenever an SQL statement retrieves or affects zero rows. (This condition is not an error, but you might be interested in handling it specially.)
action can be one of the following:
This effectively means that the condition is ignored. This is the default.
Jump to the specified label (using a COBOL goto statement).
Print a message to standard error. This is useful for simple programs or during prototyping. The details of the message cannot be configured.
Call STOP, which will terminate the program.
Call the specified functions with the following characters including arguments. Thus, syntaxes (including compiler depending) are able to be placed as well as the arguments. Though, there are some limitation as following:
You can't use RETURNING, ON EXCEPTION or OVER FLOW clauses.
In the called subprogram, You must specify CONTINUE for every action with WHENEVER statement.
The SQL standard only provides for the actions CONTINUE and GOTO (and GO TO).
Here is an example that you might want to use in a simple program. It prints a simple message when a warning occurs and aborts the program when an error happens:
EXEC SQL WHENEVER SQLWARNING SQLPRINT END-EXEC. EXEC SQL WHENEVER SQLERROR STOP END-EXEC.
The statement EXEC SQL WHENEVER is a directive of the SQL preprocessor, not a COBOL statement. The error or warning actions that it sets apply to all embedded SQL statements that appear below the point where the handler is set, unless a different action was set for the same condition between the first EXEC SQL WHENEVER and the SQL statement causing the condition, regardless of the flow of control in the COBOL program. So neither of the two following COBOL program excerpts will have the desired effect:
* * WRONG * ... IF VERBOSE = 1 THEN EXEC SQL WHENEVER SQLWARNING SQLPRINT END-EXEC END-IF. ... EXEC SQL SELECT ... END-EXEC. ... * * WRONG * ... CALL SET-ERROR-HANDLER. * (and execute "EXEC SQL WHENEVER SQLERROR STOP" in SET-ERROR-HANDLER) ... EXEC SQL SELECT ... END-EXEC. ...