7.7.4. WHEN …​ DO

Used for

Catching an exception and handling the error

Available in

PSQL

Syntax

  1. WHEN {<error> [, <error> …] | ANY}
  2. DO <compound_statement>
  3. <error> ::=
  4. { EXCEPTION exception_name
  5. | SQLCODE number
  6. | GDSCODE errcode }
Table 96. WHEN …​ DO Statement Parameters
ArgumentDescription

exception_name

Exception name

number

SQLCODE error code

errcode

Symbolic GDSCODE error name

compound_statement

A statement or a block of statements

The WHEN …​ DO statement is used to handle errors and user-defined exceptions. The statement catches all errors and user-defined exceptions listed after the keyword WHEN keyword. If WHEN is followed by the keyword ANY, the statement catches any error or user-defined exception, even if they have already been handled in a WHEN block located higher up.

The WHEN …​ DO block must be located at the very end of a block of statements, before the block’s END statement.

The keyword DO is followed by a statement, or a block of statements inside a BEGIN …​ END block, that handle the exception. The SQLCODE, GDSCODE, and SQLSTATE context variables are available in the context of this statement or block. The EXCEPTION statement, without parameters, can also be used in this context to re-throw the error or exception.

Targeting GDSCODE

The argument for the WHEN GDSCODE clause is the symbolic name associated with the internally-defined exception, such as grant_obj_notfound for GDS error 335544551.

After the DO clause, another GDSCODE context variable, containing the numeric code, becomes available for use in the statement or the block of statements that code the error handler. That numeric code is required if you want to compare a GDSCODE exception with a targeted error.

The WHEN …​ DO statement or block is never executed unless one of the events targeted by its conditions occurs in run-time. If the statement is executed, even if it actually does nothing, execution will continue as if no error occurred: the error or user-defined exception neither terminates nor rolls back the operations of the trigger or stored procedure.

However, if the WHEN …​ DO statement or block does nothing to handle or resolve the error, the DML statement (SELECT, INSERT, UPDATE, DELETE, MERGE) that caused the error will be rolled back and none of the statements below it in the same block of statements are executed.

  1. If the error is not caused by one of the DML statements (SELECT, INSERT, UPDATE, DELETE, MERGE), the entire block of statements will be rolled back, not just the one that caused an error. Any operations in the WHEN …​ DO statement will be rolled back as well. The same limitation applies to the EXECUTE PROCEDURE statement. Read an interesting discussion of the phenomenon in Firebird Tracker ticket CORE-4483.

  2. In selectable stored procedures, output rows that were already passed to the client in previous iterations of a FOR SELECT …​ DO …​ SUSPEND loop remain available to the client if an exception is thrown subsequently in the process of retrieving rows.

Scope of a WHEN …​ DO Statement

A WHEN …​ DO statement catches errors and exceptions in the current block of statements. It also catches similar exceptions in nested blocks, if those exceptions have not been handled in them.

All changes made before the statement that caused the error are visible to a WHEN …​ DO statement. However, if you try to log them in an autonomous transaction, those changes are unavailable, because the transaction where the changes took place is not committed at the point when the autonomous transaction is started. Example 4, below, demonstrates this behaviour.

When handling exceptions, it is sometimes desirable to handle the exception by writing a log message to mark the fault and having execution continue past the faulty record. Logs can be written to regular tables but there is a problem with that: the log records will “disappear” if an unhandled error causes the module to stop executing and a rollback ensues. Use of external tables can be useful here, as data written to them is transaction-independent. The linked external file will still be there, regardless of whether the overall process succeeds or not.

Examples using WHEN…​DO

  1. Replacing the standard error with a custom one:

    1. CREATE EXCEPTION COUNTRY_EXIST '';
    2. SET TERM ^;
    3. CREATE PROCEDURE ADD_COUNTRY (
    4. ACountryName COUNTRYNAME,
    5. ACurrency VARCHAR(10) )
    6. AS
    7. BEGIN
    8. INSERT INTO country (country, currency)
    9. VALUES (:ACountryName, :ACurrency);
    10. WHEN SQLCODE -803 DO
    11. EXCEPTION COUNTRY_EXIST 'Country already exists!';
    12. END^
    13. SET TERM ^;
  2. Logging an error and re-throwing it in the WHEN block:

    1. CREATE PROCEDURE ADD_COUNTRY (
    2. ACountryName COUNTRYNAME,
    3. ACurrency VARCHAR(10) )
    4. AS
    5. BEGIN
    6. INSERT INTO country (country,
    7. currency)
    8. VALUES (:ACountryName,
    9. :ACurrency);
    10. WHEN ANY DO
    11. BEGIN
    12. -- write an error in log
    13. IN AUTONOMOUS TRANSACTION DO
    14. INSERT INTO ERROR_LOG (PSQL_MODULE,
    15. GDS_CODE,
    16. SQL_CODE,
    17. SQL_STATE)
    18. VALUES ('ADD_COUNTRY',
    19. GDSCODE,
    20. SQLCODE,
    21. SQLSTATE);
    22. -- Re-throw exception
    23. EXCEPTION;
    24. END
    25. END
  3. Handling several errors in one WHEN block

    1. ...
    2. WHEN GDSCODE GRANT_OBJ_NOTFOUND,
    3. GDSCODE GRANT_FLD_NOTFOUND,
    4. GDSCODE GRANT_NOPRIV,
    5. GDSCODE GRANT_NOPRIV_ON_BASE
    6. DO
    7. BEGIN
    8. EXECUTE PROCEDURE LOG_GRANT_ERROR(GDSCODE);
    9. EXIT;
    10. END
    11. ...

See also

EXCEPTION, CREATE EXCEPTION, SQLCODE and GDSCODE Error Codes and Message Texts and SQLSTATE Codes and Message Texts