Challenge - 5 Problems
Exception Handling Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
What is the output of this exception block?
Consider the following PL/pgSQL block. What will be the output after execution?
PostgreSQL
DO $$ DECLARE result TEXT := ''; BEGIN BEGIN RAISE EXCEPTION 'Error occurred'; EXCEPTION WHEN OTHERS THEN result := 'Exception caught'; END; RAISE NOTICE '%', result; END $$;
Attempts:
2 left
💡 Hint
Look at how the inner BEGIN-EXCEPTION-END block handles the error.
✗ Incorrect
The inner block raises an exception, which is caught by the EXCEPTION clause, setting result to 'Exception caught'. The outer block then raises a notice with that value.
📝 Syntax
intermediate2:00remaining
Identify the syntax error in this exception block
Which option correctly identifies the syntax error in this PL/pgSQL code snippet?
PostgreSQL
DO $$
BEGIN
BEGIN
RAISE EXCEPTION 'Oops';
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'Caught';
END;
END $$;Attempts:
2 left
💡 Hint
Check the syntax of the EXCEPTION WHEN clause.
✗ Incorrect
In PL/pgSQL, the WHEN clause must be followed by THEN before the handler code.
❓ optimization
advanced2:00remaining
Optimize exception handling to avoid unnecessary overhead
Which option shows the best practice to avoid performance overhead when no exception is expected?
PostgreSQL
DO $$ BEGIN -- Some code that rarely raises exceptions PERFORM some_function(); EXCEPTION WHEN OTHERS THEN RAISE NOTICE 'Exception caught'; END $$;
Attempts:
2 left
💡 Hint
Exception handling adds overhead even if no error occurs.
✗ Incorrect
If exceptions are rare and can be handled at a higher level, removing the EXCEPTION block improves performance.
🔧 Debug
advanced2:00remaining
Does this exception block catch the error?
Given this PL/pgSQL block, which statement about the exception handling is correct?
PostgreSQL
DO $$ BEGIN PERFORM 1/0; EXCEPTION WHEN division_by_zero THEN RAISE NOTICE 'Division by zero caught'; END $$;
Attempts:
2 left
💡 Hint
Check the exact exception name or SQLSTATE code for division by zero in PostgreSQL.
✗ Incorrect
The exception name 'division_by_zero' is a predefined condition name corresponding to SQLSTATE '22012' and will correctly catch the division by zero error.
🧠 Conceptual
expert3:00remaining
What happens when an exception is re-raised inside an EXCEPTION block?
Consider this PL/pgSQL block. What will be the final output?
PostgreSQL
DO $$
BEGIN
BEGIN
RAISE EXCEPTION 'Initial error';
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'Caught error';
RAISE;
END;
EXCEPTION
WHEN OTHERS THEN
RAISE NOTICE 'Outer handler caught error';
END $$;Attempts:
2 left
💡 Hint
Think about how re-raising an exception propagates it to outer blocks.
✗ Incorrect
The inner block catches and raises a notice, then re-raises the exception. The outer block catches it and raises another notice.