Sub topic 11
Errors raised in declarations and inside handlers
An EXCEPTION section does not protect an entire block. It protects only the executable section between BEGIN and EXCEPTION. This chapter covers the two places a handler cannot reach: the declaration section of its own block, and the handlers themselves. It assumes you can write WHEN clauses, nest blocks, and read SQLERRM. To see the output, run SET SERVEROUTPUT ON in SQL*Plus or SQLcl first.
The rule in one sentence
An exception raised in a block's declaration section or in one of its handlers propagates to the enclosing block. The handlers of the same block never see it.
| Where the error is raised | Handled by this block's `EXCEPTION` section? | Where it goes |
|---|---|---|
| Executable section (`BEGIN` to `EXCEPTION`) | Yes | Matching `WHEN` clause |
| Declaration section (`DECLARE` or `IS`) | No | Enclosing block or caller |
| Inside a `WHEN` clause body | No | Enclosing block or caller |
Errors in the declaration section
A declaration such as l_code VARCHAR2(3) := 'ABCDE'; runs an assignment at the moment the block starts. If the assignment fails, the block never begins executing, so its handlers are never active.
BEGIN
DECLARE
l_code VARCHAR2(3) := 'ABCDE';
BEGIN
DBMS_OUTPUT.PUT_LINE('never reached');
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('inner handler');
END;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Outer handler caught: ' || SQLERRM);
END;
/The output is Outer handler caught: ORA-06502: PL/SQL: numeric or value error: character string buffer too small. The inner WHEN VALUE_ERROR clause matches the error type, but it cannot run because the failure happened before the inner block's executable section started.
The fix: initialize in the executable section
If a default value can fail, assign it after BEGIN, where your own handler covers it.
DECLARE
l_code VARCHAR2(3);
BEGIN
l_code := 'ABCDE';
EXCEPTION
WHEN VALUE_ERROR THEN
l_code := 'ERR';
DBMS_OUTPUT.PUT_LINE('Default replaced with ' || l_code);
END;
/Keep declarations to literals and values that cannot fail. Put anything that calls a function, converts a type, or depends on a parameter after BEGIN.
Subprograms behave the same way
A stored procedure or function is also a block. An error in its declarations goes to the caller, even if the procedure has WHEN OTHERS.
CREATE OR REPLACE PROCEDURE show_name (
p_emp_id IN employees.employee_id%TYPE
) IS
l_name VARCHAR2(5) := LPAD('x', 10, 'x');
BEGIN
DBMS_OUTPUT.PUT_LINE(l_name || p_emp_id);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('handled inside');
END show_name;
/
BEGIN
show_name(100);
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Caller saw: ' || SQLERRM);
END;
/handled inside is never printed. The caller prints Caller saw: ORA-06502: .... This surprises people who assume a WHEN OTHERS at the bottom of a procedure makes the procedure unable to fail. Parameter default values and %TYPE references fall under the same rule, because they are evaluated during the call and before the body starts.
The same applies to a package's initialization section and to anything that fails while a package is being instantiated. The caller of the first package reference receives the error.
Errors raised inside a handler
A handler is ordinary code, so it can fail too. The exception it raises is not offered to the other WHEN clauses in the same EXCEPTION section. It goes straight to the enclosing block.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Handling missing row');
RAISE_APPLICATION_ERROR(-20010, 'Employee lookup failed');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Not reached for this error');
END;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Outer saw: ' || SQLERRM);
END;
/The output is two lines: Handling missing row and Outer saw: ORA-20010: Employee lookup failed. The sibling WHEN OTHERS in the inner block is skipped. Only one handler in a given EXCEPTION section ever runs, and an error inside it leaves the block.
Raising a new error on purpose, as above, is a common way to translate a low-level error into an application error. Raising one by accident is the problem.
The original error is replaced
When a handler raises a different exception, the original one is gone. SQLERRM and SQLCODE now describe the new error. The backtrace points at the line in the handler that raised, not at the line that first failed. If you still need the original details, copy them into variables before doing anything else in the handler.
A plain RAISE; is different. It re-raises the exception being handled and keeps its original backtrace, which is why it is the right way to pass an error upward unchanged.
Protecting risky work inside a handler
Handlers often do work that can fail: writing to a log table, calling a procedure, or formatting a message. If that work fails, the caller sees the logging error and the real problem disappears. Wrap risky handler work in its own inner block, and save the original message first.
CREATE TABLE error_log (
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP,
message VARCHAR2(4000)
);
DECLARE
l_orig VARCHAR2(4000);
BEGIN
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN OTHERS THEN
l_orig := SQLERRM;
BEGIN
INSERT INTO error_log (message) VALUES (l_orig);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Logging failed: ' || SQLERRM);
END;
RAISE;
END;
/If the INSERT fails (for example, the table is missing or full), the inner handler reports the logging failure and the block continues. The final RAISE; then re-raises the original divide-by-zero error, ORA-01476, so the caller still sees the real failure. Without the inner block, a failed INSERT would replace ORA-01476 with a logging error.
Notice that l_orig := SQLERRM; comes first. Inside the inner WHEN OTHERS, SQLERRM refers to the logging error, not the original.
Errors in the exception section of a loop body
The same rule decides how you structure loops. A handler on the outer block cannot resume the loop, because control leaves the block. To keep going after a failure, the handler must belong to a block inside the loop body, as in the raise_salary loop from earlier chapters. If an error occurs in that inner handler, it ends the loop, so keep inner handlers small.
Summary of practical rules
- Initialize variables whose values can fail in the executable section, not in
DECLARE. - Assume a subprogram's own
EXCEPTIONsection never covers its parameters, declarations, or defaults. - Capture
SQLCODE,SQLERRM, and the backtrace into variables at the start of a handler if the handler does more work. - Wrap logging or cleanup in an inner block so that its failure does not hide the original error.
- Use
RAISE;to re-raise unchanged. UseRAISE_APPLICATION_ERRORonly when you mean to replace the error.
Exercise
In the block below, which handler prints a message, and what does it print? DECLARE ln NUMBER(2) := 100; BEGIN NULL; EXCEPTION WHEN OTHERS THEN DBMSOUTPUT.PUT_LINE('handled'); END; /
Show answer
None. The assignment of 100 to NUMBER(2) fails in the declaration section with ORA-06502, which this block's WHEN OTHERS cannot catch. The error is unhandled and reaches the caller (SQL*Plus displays it), and "handled" is never printed. To handle it, assign l_n after BEGIN, or put the block inside an outer block that has a handler.
Exercise
A handler for NODATAFOUND calls a logging procedure that raises ORA-20050. The same EXCEPTION section also has WHEN OTHERS. Does WHEN OTHERS catch ORA-20050? What does the caller of the block see, and how would you make the caller see the original NODATAFOUND instead?
Show answer
No. An error raised inside a handler is not passed to the sibling WHEN clauses of the same EXCEPTION section. It propagates to the enclosing block, so the caller sees ORA-20050 and the NODATAFOUND is lost. To keep the original error, wrap the logging call in its own inner BEGIN ... EXCEPTION ... END block that handles or ignores logging failures, and then use RAISE; to re-raise NODATAFOUND.