Sub topic 8
Handling and raising errors in subprograms
Prerequisites
This chapter assumes you can write an anonymous block with an EXCEPTION section and that you have created a procedure and a function with CREATE OR REPLACE. It reuses raise_salary and get_full_name from earlier chapters, and the employees table from the HR sample schema.
How an exception travels
When a statement fails, PL/SQL raises an exception and stops running the current block's executable section. It then looks for a matching handler in that block's EXCEPTION section. If it finds none, the exception propagates to the caller, which repeats the search in its own block. If no block handles it, the exception reaches the client as an error such as ORA-20001.
Two consequences follow:
- A subprogram that handles an exception completes normally from the caller's point of view. The caller never sees the error unless you re-raise it.
- A subprogram that does not handle an exception hands the decision to its caller. This is often the right choice.
Handling predefined exceptions
Oracle names the most common errors. You can catch them by name.
| Exception | Error | Typical cause |
|---|---|---|
| `NO_DATA_FOUND` | ORA-01403 | `SELECT ... INTO` returned no row |
| `TOO_MANY_ROWS` | ORA-01422 | `SELECT ... INTO` returned more than one row |
| `ZERO_DIVIDE` | ORA-01476 | Division by zero |
| `VALUE_ERROR` | ORA-06502 | Value too large or wrong type for a variable |
| `DUP_VAL_ON_INDEX` | ORA-00001 | Unique constraint violated |
| `INVALID_NUMBER` | ORA-01722 | Failed character-to-number conversion in SQL |
SELECT ... INTO is the main source of trouble because it demands exactly one row. The function below treats "no row" as a normal outcome and "several rows" as an error the caller must hear about:
CREATE OR REPLACE FUNCTION get_employee_id_by_last_name (
p_last_name IN employees.last_name%TYPE
) RETURN employees.employee_id%TYPE AS
v_id employees.employee_id%TYPE;
BEGIN
SELECT employee_id
INTO v_id
FROM employees
WHERE last_name = p_last_name;
RETURN v_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
WHEN TOO_MANY_ROWS THEN
RAISE_APPLICATION_ERROR(-20002, 'Last name is not unique: ' || p_last_name);
END get_employee_id_by_last_name;
/Returning NULL for a missing row is a design choice. It works well for lookups, but a caller can forget to test for NULL. For operations such as raise_salary, where silence would hide a failure, raise an error instead.
Raising errors with RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR(error_number, message) stops the subprogram and sends a numbered error to the caller. The number must be between -20000 and -20999. The message can be up to 2048 bytes. The raise_salary procedure from the spine uses it:
CREATE OR REPLACE PROCEDURE raise_salary (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
UPDATE employees
SET salary = salary * (1 + p_percent / 100)
WHERE employee_id = p_employee_id;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Employee not found: ' || p_employee_id);
END IF;
END raise_salary;
/The caller sees this as ORA-20001: Employee not found: 9999. Oracle reserves the numbers outside the -20000 to -20999 range for its own errors, and passing one of them raises ORA-21000.
Naming user-defined errors with EXCEPTION_INIT
A caller that wants to handle ORA-20001 specifically has no name to write in a WHEN clause. PRAGMA EXCEPTION_INIT binds a name to an error number:
SET SERVEROUTPUT ON
DECLARE
e_employee_missing EXCEPTION;
PRAGMA EXCEPTION_INIT(e_employee_missing, -20001);
BEGIN
raise_salary(p_employee_id => 9999);
EXCEPTION
WHEN e_employee_missing THEN
DBMS_OUTPUT.PUT_LINE('Caught: ' || SQLERRM);
END;
/The output is Caught: ORA-20001: Employee not found: 9999.
In a larger system, declare these named exceptions and their numbers once in a package specification. Callers and the subprograms that raise them then share one definition, and the numbers cannot drift apart.
Catching everything, and why to be careful
WHEN OTHERS matches any exception that no earlier handler matched. It is useful for logging and cleanup. It becomes dangerous when it swallows the error:
EXCEPTION
WHEN OTHERS THEN
NULL; -- the failure disappears; the caller assumes successIf you use WHEN OTHERS, do something useful and then re-raise with a bare RAISE. A bare RAISE passes the original exception on unchanged:
CREATE OR REPLACE PROCEDURE raise_salary_logged (
p_employee_id IN employees.employee_id%TYPE,
p_percent IN NUMBER DEFAULT 10
) AS
BEGIN
raise_salary(p_employee_id, p_percent);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('raise_salary failed: ' || SQLERRM);
DBMS_OUTPUT.PUT_LINE(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE;
END raise_salary_logged;
/SQLCODE and SQLERRM return the current error number and message inside a handler. DBMS_UTILITY.FORMAT_ERROR_BACKTRACE returns the chain of subprogram names and line numbers where the error was raised. Call it inside the handler, before anything else raises and replaces the error.
A related trap is RAISE_APPLICATION_ERROR inside a WHEN OTHERS handler. It replaces the original error, and the original stack is lost. Pass TRUE as the third argument to keep the earlier errors on the error stack:
RAISE_APPLICATION_ERROR(-20010, 'Salary update failed', TRUE);Where a handler does not apply
A handler only covers the executable section of its own block. Three situations catch people out:
- An exception raised in the declaration section, such as
v_code VARCHAR2(2) := 'ABC';, is not caught by that block'sEXCEPTIONsection. It goes straight to the caller asORA-06502. - An exception raised inside a handler is not caught by sibling handlers in the same block. It propagates outward.
- A function that reaches
ENDwithout executingRETURNraisesORA-06503: Function returned without value. Put aRETURNon every path, including in the handlers.
To protect a risky initialization, move it into an inner block:
BEGIN
DECLARE
v_code VARCHAR2(2) := 'ABC';
BEGIN
NULL;
END;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Initialization failed: ' || SQLERRM);
END;
/Errors and transactions
Handling an exception does not undo earlier work. If raise_salary updates a row and a later statement in the same subprogram fails and is handled, the update stays in your transaction. Roll it back yourself with ROLLBACK or ROLLBACK TO savepoint_name if the work must be all or nothing.
If an exception leaves the outermost call unhandled, Oracle rolls back the changes that call made. It does not undo a COMMIT that the subprogram or one of its callees already executed.
Parameters behave in a related way. When a subprogram ends with an unhandled exception, the values of its OUT and IN OUT parameters are normally not copied back to the caller's variables. The NOCOPY hint, covered in a later chapter, can change this.
Practical rules
- Catch an exception only where you can do something about it: supply a default, clean up, or translate it into a clearer error.
- Use
RAISE_APPLICATION_ERRORfor conditions that belong to your application's rules, and keep the numbers in one documented place. - Do not end a
WHEN OTHERShandler withoutRAISEorRAISE_APPLICATION_ERROR. - Log the backtrace where you handle the error, not where you raise it.
Exercise
A procedure ends with EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);. A caller runs it, sees no error, and commits. What went wrong, and what is the smallest change that fixes it?
Show answer
The handler logs the message and then ends normally, so the exception is consumed. The caller sees a successful call and commits whatever partial work was done. Add a bare RAISE; as the last statement of the handler so the original error reaches the caller.
Exercise
Write an anonymous block that calls get_employee_id_by_last_name('Smith') and prints a different message when the function raises ORA-20002. Which declaration lets you name that exception in a WHEN clause?
Show answer
Declare e_not_unique EXCEPTION; and PRAGMA EXCEPTION_INIT(e_not_unique, -20002); in the block's declaration section. Then call the function in the executable section and add WHEN e_not_unique THEN DBMS_OUTPUT.PUT_LINE('Ambiguous name'); in the EXCEPTION section.