Sub topic 2
Writing an EXCEPTION section with WHEN clauses
This chapter assumes you can write a basic PL/SQL block (DECLARE, BEGIN, END), declare variables with %TYPE, and use IF and LOOP. The examples use the Oracle HR sample schema and DBMS_OUTPUT. In SQLPlus or SQLDeveloper, run SET SERVEROUTPUT ON first.
Where the EXCEPTION section sits
A PL/SQL block has up to three sections. The EXCEPTION section is the optional last one, between the executable statements and END:
DECLARE
-- declarations (optional)
BEGIN
-- executable statements (required)
EXCEPTION
-- handlers (optional)
END;
/Each handler is a WHEN clause. It names one or more exceptions and gives the statements to run when one of them is raised:
EXCEPTION
WHEN exception_name_1 THEN
statements;
WHEN exception_name_2 OR exception_name_3 THEN
statements;
WHEN OTHERS THEN
statements;OTHERS is a catch-all, covered in detail in a later chapter. Here it only matters for where it goes in the list.
How control moves
When a statement in the executable section raises an exception, PL/SQL stops running that section at once. It does not run the remaining statements. It searches the EXCEPTION section of the same block, top to bottom, for the first WHEN clause that matches. If it finds one, it runs that handler. When the handler finishes, the block ends normally and control returns to whatever follows the block's END.
The "continues after END" rule surprises many learners. Execution never goes back to the statement that failed, and it never goes on to the next statement in the same section.
DECLARE
l_divisor NUMBER := 0;
BEGIN
DBMS_OUTPUT.PUT_LINE('Step 1');
DBMS_OUTPUT.PUT_LINE('Step 2: ' || 10 / l_divisor);
DBMS_OUTPUT.PUT_LINE('Step 3');
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('Division by zero');
END;
/The output is Step 1 and then Division by zero. Step 3 never runs, because the block is finished once the handler completes.
A first handler
This block looks up one employee. SELECT ... INTO must return exactly one row. Zero rows raise NO_DATA_FOUND, and more than one row raises TOO_MANY_ROWS. Each has its own handler:
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
DBMS_OUTPUT.PUT_LINE(l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that ID');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one employee matched');
END;
/No employee has ID 9999, so NO_DATA_FOUND is raised. The DBMS_OUTPUT.PUT_LINE(l_name) line is skipped, and the first handler prints its message.
Sharing one handler with OR
If two exceptions need the same response, join them with OR in one WHEN clause:
DECLARE
l_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO l_salary
FROM employees
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE('Salary: ' || l_salary);
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Expected exactly one row');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected error: ' || SQLERRM);
RAISE;
END;
/Department 50 has many employees in the HR sample data, so TOO_MANY_ROWS is raised and the first handler runs. Use OR only when the response really is identical. If you need to know which exception occurred, write separate clauses.
OR joins exception names only. You cannot write WHEN NO_DATA_FOUND AND ..., and you cannot add a boolean condition to a WHEN clause. A handler matches by exception, never by a test on data.
Rules for handler order and uniqueness
| Rule | What happens if you break it |
|---|---|
| Handlers are checked top to bottom and only the first match runs | A later clause that also matches is never reached |
| `WHEN OTHERS` must be the last handler | The block does not compile (PLS-00370) |
| An exception may appear in only one handler of a block | The block does not compile (PLS-00483) |
| At most one handler runs per exception | No fall-through to the next `WHEN` clause, so no `break` is needed |
Because the compiler rejects duplicates and an early OTHERS, ordering among named exceptions rarely matters. A named exception can only appear once, so the clauses do not overlap. The main exception is OTHERS, which overlaps everything and so goes last.
BEGIN
NULL;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Caught');
WHEN NO_DATA_FOUND THEN -- PLS-00370: OTHERS must be last
DBMS_OUTPUT.PUT_LINE('Never reachable');
END;
/What a handler can and cannot catch
A block's EXCEPTION section protects only the statements in that block's own BEGIN section. Two limits follow from this.
- Errors in the declaration section are not caught by the same block. If
l_name VARCHAR2(2) := 'Smith';fails with a value error, the exception goes to the enclosing block or the caller, not to this block's handlers. - Errors raised inside a handler are not caught by sibling handlers. If a
WHENclause itself raises an exception, the otherWHENclauses of that block do not see it. It propagates outward.
Later chapters cover both cases in depth. For now, remember that a handler guards the executable section only.
A handler also does not undo anything on its own account. The work the block did before the error stays in the current transaction unless you roll it back, which a later chapter covers.
Continuing after an error with an inner block
Since the enclosing block ends after its handler runs, a loop cannot "skip and go on" if the handler sits outside it. To keep going, wrap the risky statements in their own inner block with its own handler. The error is then handled inside the loop body, and the next iteration starts normally:
DECLARE
TYPE t_ids IS TABLE OF employees.employee_id%TYPE;
l_ids t_ids := t_ids(100, 9999, 101);
l_name employees.last_name%TYPE;
BEGIN
FOR i IN 1 .. l_ids.COUNT LOOP
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = l_ids(i);
DBMS_OUTPUT.PUT_LINE(l_ids(i) || ': ' || l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(l_ids(i) || ': not found');
END;
END LOOP;
END;
/IDs 100 and 101 print their names, and 9999 prints not found. The loop visits all three values. If the EXCEPTION section were placed on the outer block instead, the loop would end at 9999 and ID 101 would never be read.
When no handler matches
If no WHEN clause in the block matches, and there is no OTHERS, the exception leaves the block. It goes to the enclosing block, or to the caller if this is the outermost block. If nothing handles it anywhere, the caller sees an error such as ORA-01403: no data found. In SQL*Plus, an anonymous block that ends this way also rolls back only its own failed statement. The rest of the session's work is untouched. The details of this are in the chapter on propagation.
Common mistakes
- Expecting execution to resume. After the handler runs, control does not return to the failing statement. Use an inner block when you need to continue.
- Putting
WHEN OTHERSfirst. The compiler rejects it. Always put it last. - Listing the same exception twice. Combine the two bodies into one clause, or distinguish them in code with
IF. - Putting the handler in the wrong block. A handler only covers its own block's executable section. Check which
BEGIN ... ENDthe failing statement is in. - Writing a handler that hides the error. A
WHENclause that prints a message and does nothing else makes the caller believe the call succeeded. Decide on purpose whether to swallow the error or re-raise it.
Exercise
A block contains SELECT ... INTO followed by two DBMS_OUTPUT.PUT_LINE calls. The SELECT returns no rows, and the block has WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('none');. Which lines are printed, and does the code after the block's END run?
Show answer
Only none is printed. The two PUT_LINE calls after the SELECT are skipped because control jumps to the handler as soon as NO_DATA_FOUND is raised. When the handler finishes, the block ends normally, so any code after the block's END does run.
Exercise
Rewrite this so the loop reports every ID that has no matching row and still processes the rest: a FOR loop with SELECT ... INTO in its body and a single EXCEPTION section at the end of the outer block. Where does the handler go?
Show answer
Put an inner BEGIN ... EXCEPTION WHEN NO_DATA_FOUND THEN ... END; inside the loop body, around the SELECT. The handler then runs for that iteration only, and the loop moves on to the next ID. A handler at the end of the outer block would end the whole block at the first missing ID.