Sub topic 10
How exceptions propagate through nested blocks and calls
This chapter assumes you can write a basic EXCEPTION section with WHEN clauses, you know the difference between predefined and user-defined exceptions, and you can read a procedure that calls another procedure. It covers where an exception goes when the block that raised it has no matching handler.
The search rule
When an exception is raised in the executable section of a block, PL/SQL stops running that block and looks for a handler in the same block. The search then follows these steps:
- If a WHEN clause in that block matches the exception, its statements run. The block then ends normally.
- If no clause matches, the exception is raised again in the enclosing block. It appears at the point where the inner block began.
- The search repeats in the enclosing block, then in its enclosing block, and so on.
- If the outermost block has no match, the exception goes to the caller. For a top-level call this means the host environment, such as SQL*Plus or your application, receives the error.
A matching handler is either a WHEN clause naming that exception or a WHEN OTHERS clause. Handlers are checked in the order written, and the first match wins.
Nested blocks
The next example raises ZERODIVIDE in an inner block whose only handler is for NODATA_FOUND.
SET SERVEROUTPUT ON
DECLARE
l_divisor NUMBER := 0;
BEGIN
DBMS_OUTPUT.PUT_LINE('1: outer starts');
BEGIN
DBMS_OUTPUT.PUT_LINE('2: inner starts');
DBMS_OUTPUT.PUT_LINE('3: ' || (10 / l_divisor));
DBMS_OUTPUT.PUT_LINE('4: not reached');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('inner handler');
END;
DBMS_OUTPUT.PUT_LINE('5: not reached');
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('6: outer handler caught ZERO_DIVIDE');
END;
/The output is lines 1, 2, and 6. The inner block has no ZERO_DIVIDE handler, so the exception moves to the outer block. Line 5 never runs, because the outer block's executable section was abandoned when the exception arrived.
Control does not return to the failing statement
A handler never resumes the statement that failed. After the handler finishes, the block is over, and execution continues with whatever follows that block in the enclosing code. This is why a handler in an inner block can let the outer block carry on:
SET SERVEROUTPUT ON
DECLARE
l_divisor NUMBER := 0;
BEGIN
BEGIN
DBMS_OUTPUT.PUT_LINE('result: ' || (10 / l_divisor));
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('inner: division skipped');
END;
DBMS_OUTPUT.PUT_LINE('outer: still running');
END;
/Both messages print. The inner block handled the error, so the outer block never sees it. Wrapping a statement or a loop body in its own block is the standard way to make one failure non-fatal. The fourth example in this tutorial's spine does exactly that inside a FOR loop.
Propagation through subprogram calls
A call to a procedure or function is treated like a nested block. If the called subprogram does not handle an exception, it appears in the caller at the line of the call.
CREATE OR REPLACE PROCEDURE level_c IS
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name INTO l_name
FROM employees
WHERE employee_id = -1;
END level_c;
/
CREATE OR REPLACE PROCEDURE level_b IS
BEGIN
DBMS_OUTPUT.PUT_LINE('level_b calls level_c');
level_c;
DBMS_OUTPUT.PUT_LINE('level_b finished');
END level_b;
/
CREATE OR REPLACE PROCEDURE level_a IS
BEGIN
level_b;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('level_a caught NO_DATA_FOUND');
END level_a;
/Running EXEC level_a with server output enabled prints "levelb calls levelc" and then "levela caught NODATAFOUND". Neither levelc nor levelb has a handler, so the exception passes through both. The "levelb finished" line never prints.
Intermediate procedures that only pass an exception along do not need an EXCEPTION section. Adding an empty or logging-only handler there is a common source of lost errors.
Scope of user-defined exceptions
A predefined exception such as NODATAFOUND can be named anywhere. A user-defined exception exists only in the block that declares it and in blocks nested inside that block. Once it propagates beyond that block, code outside can no longer refer to it by name.
SET SERVEROUTPUT ON
BEGIN
DECLARE
e_too_small EXCEPTION;
BEGIN
RAISE e_too_small;
END;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLCODE || ' ' || SQLERRM);
END;
/This prints 1 User-Defined Exception. The outer handler cannot say WHEN e_too_small, because that name does not exist there and the block would fail to compile. Only WHEN OTHERS can catch it. If nothing catches it, the host receives ORA-06510: PL/SQL: unhandled user-defined exception.
Two practical consequences follow:
- Declare exceptions that callers need to catch in a package specification, so the name is visible everywhere.
- Alternatively, bind the exception to an error number with PRAGMA EXCEPTIONINIT or use RAISEAPPLICATION_ERROR. Callers can then match on the error number instead of a name.
An inner block can also declare an exception with the same name as one in an outer block. The inner declaration hides the outer one. A RAISE of that name in the inner block will not match an outer WHEN clause for the outer exception, even though the names look identical.
Exceptions raised inside a handler
A handler protects only the executable section of its own block. If a statement inside a WHEN clause raises an exception, the sibling WHEN clauses of that same block do not see it. It propagates to the enclosing block, just like an unhandled error.
SET SERVEROUTPUT ON
BEGIN
BEGIN
RAISE NO_DATA_FOUND;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE TOO_MANY_ROWS;
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('never runs');
END;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('outer caught the exception raised in the handler');
END;
/The same rule applies to exceptions raised in a block's DECLARE section. A failed variable initialization is not handled by that block's own EXCEPTION section. A later chapter covers both cases in detail.
Summary of where an exception goes
| Where the exception is raised | Who can handle it |
|---|---|
| Executable section of a block | Handlers in that block, then enclosing blocks |
| Inside a called subprogram | Handlers in that subprogram, then the caller at the call line, then its callers |
| Declaration section of a block | Only the enclosing block or caller |
| Inside an exception handler | Only the enclosing block or caller |
| Not matched anywhere | The host environment, as an error |
What happens to your data
A handled exception does not roll back anything. Changes made before the error stay in the transaction, and your code decides whether to commit or roll back.
An exception that is never handled behaves differently. When it reaches the host from a top-level call, Oracle undoes the changes made by that call, because the call is treated as a single statement. Only the failed call is undone. Work you committed earlier in the session is not touched. The chapter on transactions covers savepoints and the details.
Practical guidelines
- Handle an error in the block that knows how to recover from it. Let it propagate otherwise.
- Wrap loop bodies in their own blocks when one bad row must not stop the rest.
- Do not put a catch-all handler in every intermediate subprogram. It hides the error from the layers above.
- Declare shared exceptions in a package specification so every caller can name them.
Before the exercise, read this block:
SET SERVEROUTPUT ON
BEGIN
BEGIN
RAISE NO_DATA_FOUND;
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('A');
END;
DBMS_OUTPUT.PUT_LINE('B');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('C');
END;
/Exercise
What does the block above print, and why does it not print B?
Show answer
It prints only C. The inner block has no NODATAFOUND handler, so the exception moves to the outer block, which abandons its executable section before reaching the line that prints B and runs its own handler.
Exercise
A user-defined exception is declared in an inner block and raised there, with no handler in that block. Which kind of handler in the outer block can catch it, and what does SQLCODE return?
Show answer
Only WHEN OTHERS can catch it, because the exception's name is not visible outside the declaring block. SQLCODE returns 1 for a user-defined exception that is not bound to an error number.