You can trap and raise errors in PostgreSQL by 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, and out-of-range assignments. By default, any error occurrences inside of a PL/pgSQL function cause 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...