7.8 Trapping and Handling Errors

Firebird has a useful lexicon of PSQL statements and resources for trapping errors in modules and for handling them. Firebird uses built-in exceptions that are raised for errors occurring when working DML and DDL statements.

In PSQL code, exceptions are handled by means of the WHEN statement. Handling an exception in the code involves either fixing the problem in situ, or stepping past it; either solution allows execution to continue without returning an exception message to the client.

An exception results in execution being terminated in the current block. Instead of passing the execution to the END statement, the procedure moves outward through levels of nested blocks, starting from the block where the exception is caught, searching for the code of the handler that knows about this exception. It stops searching when it finds the first WHEN statement that can handle this exception.

7.8.1 System Exceptions

An exception is a message that is generated when an error occurs.

All exceptions handled by Firebird have predefined numeric values for context variables (symbols) and text messages associated with them. Error messages are output in English by default. Localized Firebird builds are available, where error messages are translated into other languages.

Complete listings of the system exceptions can be found in Appendix B: Exception Codes and Messages:

7.8.2 Custom Exceptions

Custom exceptions can be declared in the database as persistent objects and called in the PSQL code to signal specific errors; for example, to enforce certain business rules. A custom exception consists of an identifier, and a default message of 1021 bytes. For details, see CREATE EXCEPTION.

7.8.3 EXCEPTION

Used forThrowing a user-defined exception or re-throwing an exception

Available inPSQL

Syntax

  1. EXCEPTION [
  2. exception_name
  3. [ custom_message
  4. | USING (<value_list>)]
  5. ]
  6. <value_list> ::= <val> [, <val> ...]

Table 7.8.3.1 EXCEPTION Statement Parameters

ArgumentDescription

exception_name

Exception name

custom_message

Alternative message text to be returned to the caller interface when an exception is thrown. Maximum length of the text message is 1,021 bytes

val

Value expression that replaces parameter slots in the exception message text

The EXCEPTION statement with exception_name throws the user-defined exception with the specified name. An alternative message text of up to 1,021 bytes can optionally override the exception’s default message text.

The default exception message can contain slots for parameters that can be filled when throwing an exception. To pass parameter values to an exception, use the USING clause. Considering, in left-to-right order, each parameter passed in the exception-raising statement as the Nth, with N starting at 1:

  • If the Nth parameter is not passed, its slot is not replaced

  • If a NULL parameter is passed, the slot will be replaced with the string *** null ***

  • If more parameters are passed than are defined in the exception message, the surplus ones are ignored

  • The maximum number of parameters is 9

  • The maximum message length, including parameter values, is 1053 bytes

Note

The status vector is generated this code combination isc_except, <exception number>, isc_formatted_exception, <formatted exception message>, <exception parameters>.

The error code used (isc_formatted_exception) was introduced in Firebird 3.0, so the client must be at least version 3.0, or at least use the firebird.msg from version 3.0 or higher, in order to translate the status vector to a string.

Warning

If the message contains a parameter slot number that is greater than 9, the second and subsequent digits will be treated as literal text. For example @10 will be interpreted as slot 1 followed by a literal 0.

As an example:

  1. CREATE EXCEPTION ex1
  2. 'something wrong in @ 1 @ 2 @ 3 @ 4 @ 5 @ 6 @ 7 @ 8 @ 9 @ 10 @ 11';
  3. SET TERM ^;
  4. EXECUTE BLOCK AS
  5. BEGIN
  6. EXCEPTION ex1 USING ( 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' );
  7. END^

This will produce the following output

  1. Statement failed, SQLSTATE = HY000
  2. exception 1
  3. -EX1
  4. -something wrong in abcdefghi a0 a1

Exceptions can be handled in a Section 7.8.4, WHEN …​ DO statement. If an exception is not handled in a module, then the effects of the actions executed inside this module are cancelled, and the caller program receives the exception (either the default text, or the custom text).

Within the exception-handling block — and only within it — the caught exception can be re-thrown by executing the EXCEPTION statement without parameters. If located outside the block, the re-thrown EXCEPTION call has no effect.

Note

Custom exceptions are stored in the system table RDB$EXCEPTIONS.

7.8.3.1 EXCEPTION Examples

  1. Throwing an exception upon a condition in the SHIP_ORDER stored procedure:

    1. CREATE OR ALTER PROCEDURE SHIP_ORDER (
    2. PO_NUM CHAR(8))
    3. AS
    4. DECLARE VARIABLE ord_stat CHAR(7);
    5. DECLARE VARIABLE hold_stat CHAR(1);
    6. DECLARE VARIABLE cust_no INTEGER;
    7. DECLARE VARIABLE any_po CHAR(8);
    8. BEGIN
    9. SELECT
    10. s.order_status,
    11. c.on_hold,
    12. c.cust_no
    13. FROM
    14. sales s, customer c
    15. WHERE
    16. po_number = :po_num AND
    17. s.cust_no = c.cust_no
    18. INTO :ord_stat,
    19. :hold_stat,
    20. :cust_no;
    21. IF (ord_stat = 'shipped') THEN
    22. EXCEPTION order_already_shipped;
    23. /* Other statements */
    24. END
  2. Throwing an exception upon a condition and replacing the original message with an alternative message:

    1. CREATE OR ALTER PROCEDURE SHIP_ORDER (
    2. PO_NUM CHAR(8))
    3. AS
    4. DECLARE VARIABLE ord_stat CHAR(7);
    5. DECLARE VARIABLE hold_stat CHAR(1);
    6. DECLARE VARIABLE cust_no INTEGER;
    7. DECLARE VARIABLE any_po CHAR(8);
    8. BEGIN
    9. SELECT
    10. s.order_status,
    11. c.on_hold,
    12. c.cust_no
    13. FROM
    14. sales s, customer c
    15. WHERE
    16. po_number = :po_num AND
    17. s.cust_no = c.cust_no
    18. INTO :ord_stat,
    19. :hold_stat,
    20. :cust_no;
    21. IF (ord_stat = 'shipped') THEN
    22. EXCEPTION order_already_shipped
    23. 'Order status is "' || ord_stat || '"';
    24. /* Other statements */
    25. END
  3. Using a parameterized exception:

    1. CREATE EXCEPTION EX_BAD_SP_NAME
    2. 'Name of procedures must start with' '@ 1' ':' '@ 2' '' ;
    3. ...
    4. CREATE TRIGGER TRG_SP_CREATE BEFORE CREATE PROCEDURE
    5. AS
    6. DECLARE SP_NAME VARCHAR(255);
    7. BEGIN
    8. SP_NAME = RDB$GET_CONTEXT ('DDL_TRIGGER' , 'OBJECT_NAME');
    9. IF (SP_NAME NOT STARTING 'SP_') THEN
    10. EXCEPTION EX_BAD_SP_NAME USING ('SP_', SP_NAME);
    11. END
  4. 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

See alsoCREATE EXCEPTION, Section 7.8.4, WHEN …​ DO

7.8.4 WHEN …​ DO

Used forCatching an exception and handling the error

Available inPSQL

Syntax

  1. WHEN {<error> [, <error> ...] | ANY}
  2. DO <compound_statement>
  3. <error> ::=
  4. { EXCEPTION exception_name
  5. | SQLCODE number
  6. | GDSCODE errcode
  7. | SQLSTATE sqlstate_code }

Table 7.8.4.1 WHEN …​ DO Statement Parameters

ArgumentDescription

exception_name

Exception name

number

SQLCODE error code

errcode

Symbolic GDSCODE error name

sqlstate_code

String literal with the SQLSTATE error code

compound_statement

A single statement, or a block of statements

The WHEN …​ DO statement handles Firebird 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 handles the exception. The SQLCODE, GDSCODE, and SQLSTATE context variables are available in the context of this statement or block. The RDB$ERROR function can be used the obtain the SQLCODE, GDSCODE, SQLSTATE, custom exception name and exception message. 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.

In statement or block of statements of the DO clause, a GDSCODE context variable, containing the numeric code, becomes available. That numeric code is required if you want to compare a GDSCODE exception with a targeted error. To compare it with a specific error, you need to use a numeric values, for example 335544551 for grant_obj_notfound.

Similar context variables are available for SQLCODE and SQLSTATE.

The WHEN …​ DO statement or block is only executed when one of the events targeted by its conditions occurs at run-time. If the WHEN …​ DO 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.

Important

  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 firebird#4803.

  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.

7.8.4.1 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 those nested blocks.

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.

Tip

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 is performed. 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.

7.8.4.2 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. MESSAGE)
    19. VALUES ('ADD_COUNTRY',
    20. GDSCODE,
    21. SQLCODE,
    22. SQLSTATE,
    23. RDB$ERROR(MESSAGE));
    24. -- Re-throw exception
    25. EXCEPTION;
    26. END
    27. 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. RDB$ERROR(MESSAGE);
    10. EXIT;
    11. END
    12. ...
  4. Catching errors using the SQLSTATE code

    1. EXECUTE BLOCK
    2. AS
    3. DECLARE VARIABLE I INT;
    4. BEGIN
    5. BEGIN
    6. I = 1/0;
    7. WHEN SQLSTATE '22003' DO
    8. EXCEPTION E_CUSTOM_EXCEPTION
    9. 'Numeric value out of range.';
    10. WHEN SQLSTATE '22012' DO
    11. EXCEPTION E_CUSTOM_EXCEPTION
    12. 'Division by zero.';
    13. WHEN SQLSTATE '23000' DO
    14. EXCEPTION E_CUSTOM_EXCEPTION
    15. 'Integrity constraint violation.';
    16. END
    17. END

See alsoSection 7.8.3, EXCEPTION, CREATE EXCEPTION, SQLCODE and GDSCODE Error Codes and Message Texts and SQLSTATE Codes and Message Texts, GDSCODE, SQLCODE, SQLSTATE, RDB$ERROR()