Exception handling helps your database code catch and manage errors smoothly. It stops your program from crashing and lets you fix or report problems.
Exception handling (BEGIN-EXCEPTION-END) in PostgreSQL
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
PostgreSQL
BEGIN -- your SQL statements here EXCEPTION WHEN condition THEN -- error handling code here END;
BEGIN starts a block of code.
EXCEPTION catches errors that happen inside the block.
Examples
PostgreSQL
BEGIN INSERT INTO users(id, name) VALUES (1, 'Alice'); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'User already exists'; END;
PostgreSQL
BEGIN UPDATE accounts SET balance = balance - 100 WHERE id = 10; EXCEPTION WHEN others THEN RAISE NOTICE 'An error occurred during update'; END;
Sample Program
This block tries to add an employee. If the ID is already taken, it shows a friendly notice instead of an error.
PostgreSQL
DO $$ BEGIN INSERT INTO employees(id, name) VALUES (1, 'John'); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'Employee with this ID already exists.'; END; $$;
Important Notes
You can catch specific errors like unique_violation or use WHEN others THEN to catch all errors.
Use RAISE NOTICE to show messages without stopping the program.
Exception blocks help keep your database work safe and user-friendly.
Summary
Use BEGIN-EXCEPTION-END blocks to catch and handle errors in PostgreSQL.
This helps your database code run smoothly without crashing on errors.
You can give clear messages or take special actions when errors happen.
Practice
1. What is the main purpose of using a
BEGIN-EXCEPTION-END block in PostgreSQL?easy
Solution
Step 1: Understand the role of BEGIN-EXCEPTION-END
This block is designed to catch errors that happen during the execution of SQL or PL/pgSQL code.Step 2: Identify the purpose of error handling
It allows the code to handle errors gracefully without stopping the entire process.Final Answer:
To catch and handle errors during code execution -> Option AQuick Check:
Error handling = A [OK]
Hint: Remember: BEGIN-EXCEPTION-END is for error catching [OK]
Common Mistakes:
- Thinking it speeds up queries
- Confusing it with table creation
- Assuming it backs up data
2. Which of the following is the correct syntax to start an exception block in PostgreSQL?
easy
Solution
Step 1: Recall PostgreSQL exception block syntax
PostgreSQL usesBEGIN ... EXCEPTION ... ENDto define a block with error handling.Step 2: Compare options with correct syntax
Only BEGIN ... EXCEPTION ... END matches the exact syntax used in PostgreSQL.Final Answer:
BEGIN ... EXCEPTION ... END -> Option CQuick Check:
PostgreSQL uses BEGIN-EXCEPTION-END syntax [OK]
Hint: Look for BEGIN and EXCEPTION keywords together [OK]
Common Mistakes:
- Using TRY-CATCH like other languages
- Adding extra keywords like START or FINISH
- Mixing syntax from other SQL dialects
3. What will be the output of the following PostgreSQL block?
DO $$
BEGIN
RAISE EXCEPTION 'Error happened';
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'Caught an error';
END $$;medium
Solution
Step 1: Analyze the RAISE EXCEPTION statement
The block raises an exception with message 'Error happened'.Step 2: Check the EXCEPTION block handling
The exception handler catches all errors (WHEN OTHERS) and raises a NOTICE with 'Caught an error'.Final Answer:
It prints 'Caught an error' as a notice and continues -> Option BQuick Check:
Exception caught triggers NOTICE message [OK]
Hint: WHEN OTHERS catches all errors and can raise NOTICE [OK]
Common Mistakes:
- Assuming the error stops execution
- Confusing EXCEPTION message with NOTICE
- Thinking syntax error occurs
4. Identify the error in this PostgreSQL exception block:
BEGIN
PERFORM 1/0;
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Division by zero caught';
END;medium
Solution
Step 1: Check block context
In PostgreSQL, standalone BEGIN-EXCEPTION-END blocks must be inside a DO block or function.Step 2: Verify exception name and usage
Exception name 'division_by_zero' is valid, and RAISE NOTICE is allowed inside EXCEPTION.Step 3: Identify missing DO wrapper
The code lacks DO $$ ... $$ to run as an anonymous block.Final Answer:
Missing DO $$ ... $$ wrapper for anonymous block -> Option AQuick Check:
Anonymous blocks need DO wrapper [OK]
Hint: Use DO $$ ... $$ for anonymous BEGIN blocks [OK]
Common Mistakes:
- Thinking exception name is wrong
- Believing RAISE NOTICE is invalid here
- Ignoring the need for DO wrapper
5. You want to write a PostgreSQL block that tries to insert a row into a table but if a unique constraint violation occurs, it should print 'Duplicate found' and continue without error. Which code snippet correctly implements this?
hard
Solution
Step 1: Identify correct exception name for unique constraint
PostgreSQL usesunique_violationto catch unique constraint errors.Step 2: Check the exception block syntax
The block catchesunique_violationand raises a notice 'Duplicate found' correctly.Step 3: Verify other options
Other options use incorrect exception names that do not exist in PostgreSQL.Final Answer:
BEGIN INSERT INTO users(id) VALUES(1); EXCEPTION WHEN unique_violation THEN RAISE NOTICE 'Duplicate found'; END; -> Option DQuick Check:
Use unique_violation for unique constraint errors [OK]
Hint: Use unique_violation to catch duplicate key errors [OK]
Common Mistakes:
- Using wrong exception names
- Forgetting to handle unique_violation
- Not raising a notice or message
