Exception handling
One could trap and raise errors in PostgreSQL using the exception and raise statements. Errors can be raised by violating data integrity constraints, or by performing illegal operations such as assigning text to integers, dividing an integer or float by zero, out-of-range assignments, and so on. By default, any error occurrence inside a PL/pgSQL function causes the function to abort the execution and roll back the changes. To be able to recover from errors, PL/pgSQL can trap the errors using the EXCEPTION
clause. The syntax of the exception clause is very similar to PL/pgSQL blocks. Moreover, PostgreSQL can raise errors using the RAISE
statement. To understand exception handling, let's consider the following helping function:
CREATE OR REPLACE FUNCTION check_not_null (value anyelement ) RETURNS VOID AS $$ BEGIN IF (value IS NULL) THEN RAISE EXCEPTION USING ERRCODE = 'check_violation'; END IF; END; $$ LANGUAGE plpgsql;
The check_not_null
statement is a polymorphic
function...