Sub topic 16
Exception handling guidelines and common mistakes
This chapter collects the rules that keep PL/SQL error handling honest. It assumes you can write an EXCEPTION section, know the predefined exceptions, and understand RAISE, RAISE_APPLICATION_ERROR, SQLCODE/SQLERRM, and how exceptions propagate through nested blocks. The examples use the HR sample schema, the raise_salary procedure, and the error_log table and log_error autonomous procedure from earlier chapters.
The governing principle: handle only what you can fix
A handler should do one of two things. It either recovers (supplies a default, retries, skips a row) or it adds information and passes the error on. A handler that does neither hides a failure from everyone above it.
Mistake 1: swallowing errors with WHEN OTHERS THEN NULL
BEGIN
raise_salary(100, -5);
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
/This block reports success even though raise_salary raised ORA-20001. The caller continues as if the raise happened, and nothing records what went wrong. Two details make it worse. Anything that raised before the handler ran, including out-of-memory and timeout errors, is also hidden. And any partial changes the block made stay in the transaction.
The corrected version logs and re-raises:
BEGIN
raise_salary(100, -5);
EXCEPTION
WHEN OTHERS THEN
log_error(SUBSTR(DBMS_UTILITY.FORMAT_ERROR_STACK ||
DBMS_UTILITY.FORMAT_ERROR_BACKTRACE, 1, 1000));
RAISE;
END;
/Rules for WHEN OTHERS:
- Put it last. PL/SQL requires this, and it is the only place it can appear.
- Follow it with
RAISEorRAISE_APPLICATION_ERRORunless the block truly handles every possible error. That is rare. - Prefer specific handlers first, so that each known error gets a known response.
Mistake 2: losing the original error location
SQLERRM tells you what failed, not where. If you only keep SQLERRM, a failure deep in a call chain looks the same as one at the top. Capture DBMS_UTILITY.FORMAT_ERROR_BACKTRACE in the handler where the error is first caught. Calling it in a later handler gives you the line of the later RAISE, not the original line.
Use a bare RAISE; to propagate the same exception. If you call RAISE_APPLICATION_ERROR inside a handler to translate an error, pass TRUE as the third argument to keep the earlier errors on the stack:
BEGIN
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN ZERO_DIVIDE THEN
RAISE_APPLICATION_ERROR(-20010, 'Salary recalculation failed', TRUE);
END;
/Mistake 3: using SQLCODE or SQLERRM directly in a SQL statement
PL/SQL does not allow SQLCODE or SQLERRM inside a SQL statement. Copy them to variables first:
DECLARE
l_code NUMBER;
l_msg VARCHAR2(512);
BEGIN
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN OTHERS THEN
l_code := SQLCODE;
l_msg := SQLERRM;
log_error(l_code || ': ' || l_msg);
RAISE;
END;
/Take the copies at the top of the handler. Any SQL or procedure call that runs first can reset what SQLCODE and SQLERRM return.
Mistake 4: logging into the same transaction you are about to roll back
An ordinary INSERT INTO error_log inside a handler disappears when the caller rolls back. That is why log_error uses PRAGMA AUTONOMOUS_TRANSACTION. Keep these points in mind:
- The logging procedure must commit its own work. An autonomous transaction that ends without a commit or rollback raises ORA-06519.
- Keep it small and make it as unlikely to fail as you can. Truncate messages so they fit the column. A logger that raises its own exception replaces the original error.
- Do not put business logic in autonomous transactions. They cannot see the caller's uncommitted changes, and they can deadlock against the caller if both touch the same rows.
Mistake 5: expecting a handler to catch errors from its own block's declarations or handlers
An exception raised in the DECLARE section, or inside an EXCEPTION section, is not caught by that same block's handlers. It goes to the enclosing block. A frequent case is a variable initialized with a value that is too large:
BEGIN
DECLARE
l_code VARCHAR2(3) := 'TOO LONG';
BEGIN
NULL;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Never reached');
END;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Caught by the outer block');
END;
/If initialization can fail, assign values in the executable section, or wrap the inner block as shown above.
Mistake 6: using exceptions where a plain check works
Some errors are expected. A lookup that finds nothing is not an emergency. Wrapping it in a small function keeps the handling in one place:
CREATE OR REPLACE FUNCTION get_last_name (
p_emp_id IN employees.employee_id%TYPE
) RETURN employees.last_name%TYPE IS
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name INTO l_name
FROM employees
WHERE employee_id = p_emp_id;
RETURN l_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_last_name;
/Two related points:
- Handle
NO_DATA_FOUNDandTOO_MANY_ROWSaround the single statement that can raise them. A broad handler around ten statements cannot tell which one failed. - A
SELECT ... INTOwith an aggregate and noGROUP BYalways returns exactly one row, so it never raisesNO_DATA_FOUND:
DECLARE
l_max employees.salary%TYPE;
BEGIN
SELECT MAX(salary) INTO l_max
FROM employees
WHERE department_id = 9999;
DBMS_OUTPUT.PUT_LINE(
CASE WHEN l_max IS NULL THEN 'NULL result, no exception'
ELSE TO_CHAR(l_max) END);
END;
/An EXCEPTION WHEN NO_DATA_FOUND handler around that query would be dead code, so test for NULL instead.
Mistake 7: leaving the transaction in an unknown state
When an exception leaves a subprogram unhandled, Oracle rolls back the failed statement, but not the whole transaction. Earlier statements in the same transaction stay uncommitted, and the caller decides what to do with them. If your handler swallows the error, the caller never learns that part of the work is missing.
- Do not commit or roll back inside a general-purpose handler unless the subprogram owns the transaction. Let the code at the transaction boundary decide.
- When a block must undo only its own work, set a
SAVEPOINTat its start andROLLBACK TOit in the handler, then re-raise or report. - Do not commit inside a loop to "keep the good rows". A later failure then leaves a half-processed batch that is hard to restart.
Mistake 8: unmanaged custom error numbers
RAISE_APPLICATION_ERROR accepts numbers from -20000 to -20999. If every developer picks a number ad hoc, two modules end up using -20001 for different problems, and callers cannot tell them apart. Put the numbers in one package, and bind named exceptions with PRAGMA EXCEPTION_INIT:
CREATE OR REPLACE PACKAGE app_errors AS
c_bad_percentage CONSTANT PLS_INTEGER := -20001;
c_emp_not_found CONSTANT PLS_INTEGER := -20002;
e_bad_percentage EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bad_percentage, -20001);
e_emp_not_found EXCEPTION;
PRAGMA EXCEPTION_INIT(e_emp_not_found, -20002);
END app_errors;
/PRAGMA EXCEPTION_INIT needs a literal number, so the value appears twice. Keep both in the same package, and raise with the constant (RAISE_APPLICATION_ERROR(app_errors.c_bad_percentage, 'Percentage must be positive')). Callers then write WHEN app_errors.e_bad_percentage instead of comparing SQLCODE to a magic number.
Quick reference
| Situation | Do this | Avoid this |
|---|---|---|
| Error you can recover from | Handle it in the smallest block that can fix it | A wide handler around many statements |
| Error you cannot recover from | Log, then `RAISE` | `WHEN OTHERS THEN NULL` |
| Need the error location | `FORMAT_ERROR_BACKTRACE` at the first handler | Only `SQLERRM` |
| Writing the error to a table | Autonomous procedure with its own `COMMIT` | Plain `INSERT` in the caller's transaction |
| Using `SQLCODE` in SQL | Copy to a variable first | `INSERT ... VALUES (SQLCODE)` |
| Custom errors | One package of numbers and named exceptions | Numbers scattered through the code |
Exercise
A procedure updates three tables in sequence. Its handler is EXCEPTION WHEN OTHERS THEN log_error(SQLERRM); with no RAISE. The second update fails. Describe what the caller sees and what is wrong, then give the fix.
Show answer
The caller sees a normal return, so it assumes all three updates worked. The first update is still pending in the transaction, the second failed, and the third never ran. The logged text has no backtrace. Fix it by logging DBMS_UTILITY.FORMAT_ERROR_STACK and FORMAT_ERROR_BACKTRACE (through an autonomous logger), then ending the handler with RAISE;. The caller can then roll back or decide what to do. If the procedure must undo only its own changes, set a SAVEPOINT at the start and ROLLBACK TO it before re-raising.
Exercise
This handler fails to compile. Why, and how do you fix it? EXCEPTION WHEN OTHERS THEN INSERT INTO error_log (message) VALUES (SQLERRM);
Show answer
It compiles in recent releases only if the version allows it. Even so, it is the wrong pattern: SQLERRM and SQLCODE may not be used directly in SQL statements, and the insert belongs to the caller's transaction, so a rollback erases it. Assign SQLERRM to a variable at the top of the handler, then call an autonomous logging procedure with that variable, and finish with RAISE.
Exercise
A block declares l_code VARCHAR2(3) := 'TOO LONG'; and has a WHEN VALUE_ERROR handler in the same block. Does the handler run?
Show answer
No. An exception raised in the declaration section propagates to the enclosing block. The same block's handlers do not see it. Wrap the block in an outer block with the handler, or assign the value in the executable section.