Sub topic 16
Exception Handling Guidelines and Common Mistakes
Assume that you know basic SQL, PL/SQL blocks, stored procedures, and transaction commands such as COMMIT and ROLLBACK. This chapter focuses on choosing safe handlers and avoiding errors that hide failures or damage transaction behavior.
Handle the error you expect
Prefer a specific exception handler when you know what can fail. A specific handler documents the intended recovery and avoids treating unrelated programming errors as expected conditions.
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('Employee was not found');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('The query returned more than one employee');
END;
/Do not use an exception handler as a substitute for ordinary control flow when a simple condition check is clearer. For example, use COUNT, EXISTS logic, or an update-count check when you only need to know whether a row exists.
Use `WHEN OTHERS` carefully
WHEN OTHERS matches every exception that reaches the block. It is useful at an application boundary, where you need to record diagnostic information or translate an error for a caller. It is dangerous when it silently continues.
This pattern hides failures:
EXCEPTION
WHEN OTHERS THEN
NULL;An empty handler can leave partial work in place and make the procedure appear successful. If you catch all errors, either handle the failure completely or re-raise it.
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error ' || SQLCODE || ': ' || SQLERRM);
RAISE;RAISE without an argument preserves the current exception. Avoid replacing it with a new generic message unless you intentionally want to change the error seen by the caller.
Preserve useful error context
Use SQLCODE for the numeric error code and SQLERRM for its message. For deeper diagnostics, DBMS_UTILITY.FORMAT_ERROR_STACK returns the error stack, while FORMAT_ERROR_BACKTRACE identifies the source line where the exception was raised.
| Goal | Recommended technique |
|---|---|
| Handle a known condition | Named exception such as `NO_DATA_FOUND` |
| Read the current error | `SQLCODE` and `SQLERRM` |
| Find the failing source line | `DBMS_UTILITY.FORMAT_ERROR_BACKTRACE` |
| Return a business-rule error | `RAISE_APPLICATION_ERROR` |
| Preserve an existing error | `RAISE` |
Do not log only SQLERRM when diagnosing production failures. The backtrace often distinguishes the failing statement from the handler that caught it.
Keep transaction ownership clear
An exception does not automatically roll back every change made by the session. Decide which block owns the transaction. A procedure should not issue COMMIT or ROLLBACK unexpectedly when its caller may have other pending work.
Use savepoints when a larger transaction must undo only one unit of work:
SAVEPOINT before_change;
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE department_id = 50;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO before_change;
RAISE;
END;
/An autonomous logging procedure can commit a log entry independently, but it must be used deliberately. Logging should never introduce a dependency that causes the original error handler to fail.
Avoid common mistakes
- Do not catch
WHEN OTHERSand return success. - Do not use
COMMITinside a reusable procedure without defining that contract. - Do not lose the original error by raising an unrelated message.
- Do not assume that a failed statement rolls back all earlier statements.
- Do not use
SQLCODEcomparisons when a named exception orPRAGMA EXCEPTION_INITmakes the intent clearer. - Do not expose internal database details to end users when a safe application message is sufficient.
- Do not write handlers that can themselves raise an unexamined exception.
Exercise
Why is WHEN OTHERS THEN NULL usually unsafe, and what should replace it?
Show answer
It hides the failure and can leave incomplete work appearing successful. Replace it with specific recovery when possible, or record diagnostics and use RAISE to preserve the original exception.