Sub topic 4
Catching everything with WHEN OTHERS
This chapter assumes you can write an EXCEPTION section with named WHEN clauses and handle predefined exceptions such as NO_DATA_FOUND. It also assumes you know basic COMMIT and ROLLBACK. The examples use the Oracle HR sample schema (employees, departments).
What WHEN OTHERS does
WHEN OTHERS is a handler that matches any exception raised in the block's executable section that no earlier WHEN clause named. That includes predefined exceptions, user-defined exceptions, and any ORA- error you did not anticipate.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE(l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employees in department 50');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Unexpected: ' || SQLERRM);
END;
/In the HR sample data, department 50 has many rows, so the query raises TOO_MANY_ROWS. No handler names that exception, so WHEN OTHERS runs and prints Unexpected: ORA-01422: exact fetch returns more than requested number of rows.
How handler matching works
PL/SQL checks the WHEN clauses from top to bottom and runs the first one that matches. Two rules follow from that:
WHEN OTHERSmust be the last handler in the section. If you put anotherWHENclause after it, the block fails to compile withPLS-00370.- Only one handler runs. After it finishes, control leaves the block. It does not return to the statement that failed.
A WHEN OTHERS handler also does not cover errors raised in the same block's declaration section or inside its own handlers. Those propagate outward. A later chapter covers that case.
You can combine OTHERS with nothing else in a single clause. WHEN NO_DATA_FOUND OR OTHERS is not legal.
The main danger: swallowed errors
A handler that does not re-raise tells the caller the call succeeded. This is the most common mistake with WHEN OTHERS.
CREATE OR REPLACE PROCEDURE set_salary_bad (
p_emp_id IN employees.employee_id%TYPE,
p_salary IN NUMBER
) IS
BEGIN
UPDATE employees
SET salary = p_salary
WHERE employee_id = p_emp_id;
EXCEPTION
WHEN OTHERS THEN
NULL; -- hides every error
END set_salary_bad;
/
BEGIN
set_salary_bad(100, 99999999); -- exceeds NUMBER(8,2)
DBMS_OUTPUT.PUT_LINE('Done');
END;
/The update fails with ORA-01438, the handler discards it, and the caller prints Done. Nobody learns that the salary did not change. The same happens with a handler that only prints a message with DBMS_OUTPUT, because the output may never be seen and the calling code still believes the work succeeded.
Compare this with the failure you want. Without the handler, the caller would receive ORA-01438, could roll back, and could report the problem.
Safer patterns
There are three patterns that use WHEN OTHERS without hiding errors.
Record the error, then re-raise it
A bare RAISE inside a handler re-raises the exception that is being handled. The caller sees the original error code and message.
CREATE OR REPLACE PROCEDURE set_salary (
p_emp_id IN employees.employee_id%TYPE,
p_salary IN NUMBER
) IS
BEGIN
UPDATE employees
SET salary = p_salary
WHERE employee_id = p_emp_id;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(
'set_salary failed for ' || p_emp_id || ': ' || SQLERRM);
RAISE;
END set_salary;
/Clean up, then re-raise
Use the handler to release resources that the normal path would release, such as closing a cursor or a file. Then re-raise.
DECLARE
CURSOR c_emp IS
SELECT employee_id FROM employees WHERE department_id = 50;
l_id employees.employee_id%TYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO l_id;
EXIT WHEN c_emp%NOTFOUND;
set_salary(l_id, 99999999);
END LOOP;
CLOSE c_emp;
EXCEPTION
WHEN OTHERS THEN
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
RAISE;
END;
/Convert to an application error
At a boundary, such as a procedure called from another application, you can replace internal Oracle errors with a stable application error. Passing TRUE as the third argument keeps the original error on the error stack.
CREATE OR REPLACE PROCEDURE set_salary_api (
p_emp_id IN employees.employee_id%TYPE,
p_salary IN NUMBER
) IS
BEGIN
set_salary(p_emp_id, p_salary);
EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR(
-20099,
'Could not update salary for ' || p_emp_id,
TRUE);
END set_salary_api;
/The trade-off is that callers can no longer test for the original error code directly. Use this pattern only when you want a single, documented error for the whole interface.
Where a handler of last resort belongs
WHEN OTHERS fits in a small number of places:
- At the outermost level of a job or entry-point procedure, where you record the failure and then re-raise or return an error status.
- Around one unit of work inside a loop, where you want to skip a bad row and continue. Wrap the call in its own inner block so the handler is local.
- In a handler whose only job is cleanup before a re-raise.
Inside ordinary business logic, name the exceptions you expect. If you can write WHEN NO_DATA_FOUND, do so, and let everything else propagate.
Capture error details first
Inside the handler, SQLCODE and SQLERRM describe the current exception. The next chapter covers them in detail. For now, remember one habit: copy them into local variables on the first line of the handler. If the handler runs other SQL or calls a subprogram that handles its own exceptions, the values can change before you use them.
DECLARE
l_code NUMBER;
l_msg VARCHAR2(512);
BEGIN
set_salary(100, 99999999);
EXCEPTION
WHEN OTHERS THEN
l_code := SQLCODE;
l_msg := SQLERRM;
DBMS_OUTPUT.PUT_LINE('Code ' || l_code || ': ' || l_msg);
RAISE;
END;
/Let the compiler warn you
Oracle can flag a WHEN OTHERS handler that does not end in RAISE or RAISE_APPLICATION_ERROR. Enable warnings, then compile your code. The compiler reports PLW-06009 for each such handler.
ALTER SESSION SET PLSQL_WARNINGS = 'ENABLE:ALL';
ALTER PROCEDURE set_salary_bad COMPILE;
SHOW ERRORS PROCEDURE set_salary_badThe check is not perfect, and a handler that logs and then ends the block normally is sometimes correct. Treat the warning as a prompt to confirm that the swallow is intentional.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `WHEN OTHERS THEN NULL;` | Errors vanish and the caller assumes success | Re-raise, or catch only the named exceptions you expect |
| Handler only prints a message | Output may be unseen and execution continues as if nothing failed | Log somewhere durable, then `RAISE` |
| `WHEN OTHERS` placed before a named handler | Compile error `PLS-00370` | Put `WHEN OTHERS` last |
| Using `SQLERRM` after other SQL in the handler | Message may describe a different state | Copy `SQLCODE` and `SQLERRM` to variables first |
| Using `RAISE_APPLICATION_ERROR` without `TRUE` | Original error is lost from the stack | Pass `TRUE` as the third argument when wrapping |
| Expecting the handler to cover declarations | Error escapes the block | Handle it in the enclosing block |
Exercise
A procedure updates a row and has the handler WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM); with no RAISE. A caller invokes it and then runs COMMIT. What does the caller see when the update fails, and what is the fix?
Show answer
The caller sees no exception, because the handler finished normally and control returned to it as if the call succeeded. The failed update changed nothing, but the caller then commits and may report success. The fix is to end the handler with RAISE (or RAISE_APPLICATION_ERROR(..., TRUE)) so the caller receives the error, and ideally to log it somewhere more durable than DBMS_OUTPUT.
Exercise
Why does this block fail to compile, and how do you fix it? BEGIN NULL; EXCEPTION WHEN OTHERS THEN DBMSOUTPUT.PUTLINE('error'); WHEN NODATAFOUND THEN DBMSOUTPUT.PUTLINE('none'); END;
Show answer
WHEN OTHERS must be the last handler, so Oracle reports PLS-00370. Move the WHEN NO_DATA_FOUND clause above the WHEN OTHERS clause.