The BEGIN block runs code; if an error happens, control jumps to EXCEPTION block to handle it, then ends.
Execution Sample
PostgreSQL
DO $$
BEGIN
RAISE NOTICE 'Start';
PERFORM 1/0; -- causes error
EXCEPTION
WHEN division_by_zero THEN
RAISE NOTICE 'Caught division by zero';
END $$;
This code tries to divide by zero, catches the error, and prints a message instead of stopping.
Execution Table
Step
Action
Evaluation
Result
1
Enter BEGIN block
No error yet
Proceed
2
Execute RAISE NOTICE 'Start'
Print message
Output: Start
3
Execute PERFORM 1/0
Division by zero error
Error raised, jump to EXCEPTION
4
Enter EXCEPTION block
Check error type
Matches division_by_zero
5
Execute RAISE NOTICE 'Caught division by zero'
Print message
Output: Caught division by zero
6
End block
No further code
Exit successfully
💡 Execution stops after handling the division_by_zero exception and completing the block.
Variable Tracker
Variable
Start
After Step 2
After Step 3
After Step 5
Final
Error state
None
None
division_by_zero error raised
Handled
None
Key Moments - 3 Insights
Why does the code jump to the EXCEPTION block after the error?
Because the error 'division_by_zero' occurs at step 3, PostgreSQL immediately transfers control to the EXCEPTION block to handle it, as shown in execution_table row 3 and 4.
What happens if the error type does not match any WHEN clause?
If no matching WHEN clause is found, the error is not handled inside the block and will propagate outside, causing the block to fail. This is why matching error types in EXCEPTION is important.
Does the code after the error inside BEGIN block run?
No, once an error occurs at step 3, the remaining code in BEGIN block is skipped and control moves to EXCEPTION block, as shown in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 2?
AStart
BCaught division by zero
CNo output
DError message
💡 Hint
Check the 'Result' column at step 2 in the execution_table.
At which step does the error occur that triggers the EXCEPTION block?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look for the step where 'division_by_zero error' is raised in the execution_table.
If the error was not division_by_zero but another error, what would happen?
AThe block would ignore the error and continue
BThe error would propagate outside and stop execution
CThe EXCEPTION block would handle it anyway
DThe error would be silently ignored
💡 Hint
Refer to key_moments about unmatched error types in EXCEPTION block.
Concept Snapshot
BEGIN-EXCEPTION-END block in PostgreSQL:
- BEGIN runs code normally.
- If error occurs, jump to EXCEPTION.
- EXCEPTION handles specific errors with WHEN clauses.
- After handling, block ends gracefully.
- Unhandled errors propagate outside.
Full Transcript
In PostgreSQL, exception handling uses a BEGIN block to run code. If an error happens, control jumps to the EXCEPTION block where you can handle specific errors using WHEN clauses. For example, dividing by zero causes an error that is caught and handled by printing a message. The code after the error inside BEGIN does not run. If the error type is not matched, the error propagates outside and stops execution. This mechanism helps keep your database code safe and predictable.
Practice
(1/5)
1. What is the main purpose of using a BEGIN-EXCEPTION-END block in PostgreSQL?
easy
A. To catch and handle errors during code execution
B. To speed up query execution
C. To create new tables automatically
D. To backup the database
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 A
Quick 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
A. BEGIN TRY ... EXCEPTION ... END
B. START ... EXCEPTION ... FINISH
C. BEGIN ... EXCEPTION ... END
D. TRY ... CATCH ... END
Solution
Step 1: Recall PostgreSQL exception block syntax
PostgreSQL uses BEGIN ... EXCEPTION ... END to 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 C
Quick 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
A. The block raises an error and stops execution
B. It prints 'Caught an error' as a notice and continues
C. It prints 'Error happened' as a notice
D. Syntax error due to missing semicolon
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 B
Quick 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
A. Missing DO $$ ... $$ wrapper for anonymous block
B. Incorrect exception name; should be zero_division_error
C. RAISE NOTICE cannot be used inside EXCEPTION
D. No error; block is correct
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 A
Quick 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
A. BEGIN
INSERT INTO users(id) VALUES(1);
EXCEPTION
WHEN duplicate_key THEN
RAISE NOTICE 'Duplicate found';
END;
B. BEGIN
INSERT INTO users(id) VALUES(1);
EXCEPTION
WHEN unique_error THEN
RAISE NOTICE 'Duplicate found';
END;
C. BEGIN
INSERT INTO users(id) VALUES(1);
EXCEPTION
WHEN unique_constraint THEN
RAISE NOTICE 'Duplicate found';
END;
D. BEGIN
INSERT INTO users(id) VALUES(1);
EXCEPTION
WHEN unique_violation THEN
RAISE NOTICE 'Duplicate found';
END;
Solution
Step 1: Identify correct exception name for unique constraint
PostgreSQL uses unique_violation to catch unique constraint errors.
Step 2: Check the exception block syntax
The block catches unique_violation and 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 D
Quick Check:
Use unique_violation for unique constraint errors [OK]
Hint: Use unique_violation to catch duplicate key errors [OK]