How to Use BEGIN EXCEPTION in PL/pgSQL for Error Handling
In PL/pgSQL, use a
BEGIN ... EXCEPTION ... END block to catch errors during execution and handle them without stopping the entire function. Inside the EXCEPTION block, you can specify actions for different error types using WHEN clauses.Syntax
The BEGIN ... EXCEPTION ... END block lets you run code that might cause errors and handle those errors gracefully.
Parts explained:
BEGIN: Starts the block of code to try.EXCEPTION: Starts the error handling section.WHEN: Specifies which error to catch.THEN: Defines what to do when that error happens.END: Ends the block.
sql
BEGIN
-- code that might raise an error
EXCEPTION
WHEN <error_condition> THEN
-- error handling code
END;Example
This example shows a function that tries to divide two numbers. If the divisor is zero, it catches the error and returns a message instead of failing.
sql
CREATE OR REPLACE FUNCTION safe_divide(a numeric, b numeric) RETURNS text AS $$ DECLARE result numeric; BEGIN BEGIN result := a / b; EXCEPTION WHEN division_by_zero THEN RETURN 'Error: Division by zero is not allowed'; END; RETURN 'Result is ' || result; END; $$ LANGUAGE plpgsql;
Common Pitfalls
Common mistakes when using BEGIN ... EXCEPTION include:
- Not specifying the correct error condition in
WHEN, so errors are not caught. - Using
RAISEinside the exception without proper message, causing confusion. - Not ending the block with
END;properly. - Ignoring exceptions silently without logging or handling, which can hide bugs.
sql
/* Wrong way: Missing specific error condition */ BEGIN -- risky code EXCEPTION WHEN OTHERS THEN -- catches all errors but no action or message END; /* Right way: Catch specific error and handle */ BEGIN -- risky code EXCEPTION WHEN division_by_zero THEN RAISE NOTICE 'Cannot divide by zero'; END;
Quick Reference
| Keyword | Purpose |
|---|---|
| BEGIN | Start a block of code to execute |
| EXCEPTION | Start the error handling section |
| WHEN | Catch a specific error type |
| THEN | Define actions to take when error occurs |
| END | End the block |
Key Takeaways
Use BEGIN ... EXCEPTION ... END blocks to catch and handle errors in PL/pgSQL functions.
Specify error types with WHEN clauses to handle different exceptions precisely.
Always end the block with END; to avoid syntax errors.
Avoid silent exception handling; log or handle errors clearly.
Test exception blocks to ensure they catch expected errors correctly.