PostgreSQL Exception
Summary: in this tutorial, you will learn how to catch and handle exceptions in PL/pgSQL.
Introduction to the PL/pgSQL Exception clause
When an error occurs within a block, PostgreSQL will abort the execution of that block as well as the surrounding transaction.
To recover from the error, you can use the exception
clause in the begin...end
block.
Here’s the syntax of the exception
clause:
How it works.
- First, when an error occurs between the
begin
andexception
clause, PL/pgSQL stops the execution and passes the control to theexception
section. - Second, PL/pgSQL sequentially searches for the first
condition
that matches the error. - Third, if there is a match, the corresponding
handle_exception
statements will execute and the control is passed to the statement after theend
keyword. - Finally, if no match is found, the error propagates out and can be caught by the
exception
clause of the enclosing block. If there is no enclosing block with theexception
clause, PL/pgSQL will abort the processing.
The condition names can be no_data_found
in case of a select
statement returns no rows or too_many_rows
if the select
statement returns more than one row. For a complete list of condition names on the PostgreSQL website.
It’s also possible to specify the error condition by SQLSTATE
code. For example, P0002
for no_data_found
and P0003
for too_many_rows
.
Typically, you will catch a specific exception and handle it properly.
To handle other exceptions rather than the one on the list, you can use the when others then
clause.
Handling exception examples
We’ll use the film
table from the sample database for the demonstration.
1) Handling no_data_found exception example
The following example issues an error because the film id 2000 does not exist.
Output:
The following example uses the exception
clause to catch the no_data_found
exception and report a more meaningful message:
Output:
2) Handling too_many_rows exception example
The following example illustrates how to handle the too_many_rows
exception:
Output:
In this example, the too_many_rows
exception occurs because the select into
statement returns more than one row while it is supposed to return one row.
3) Handling multiple exceptions
The following example illustrates how to catch multiple exceptions:
Output:
4) Handling exceptions as SQLSTATE codes
The following example is the same as the one above except that it uses the SQLSTATE
codes instead of the condition names:
Output:
Summary
- Use the
exception
clause in thebegin...end
block to catch and handle exceptions.