Sub topic 8
Raising and re-raising exceptions with RAISE
This chapter assumes you can read a PL/SQL block with an EXCEPTION section, that you know the predefined exceptions such as NO_DATA_FOUND, and that you have declared a user-defined exception at least once. It covers the RAISE statement: its three forms, when to use each, and the mistakes that follow from misusing them. Examples use the Oracle HR sample schema. Run them with SET SERVEROUTPUT ON.
What RAISE does
Oracle raises most exceptions for you, for example when a SELECT INTO finds no row. RAISE lets your own code raise an exception. When it runs, normal execution stops and control moves to the matching handler in the current block's EXCEPTION section. If no handler matches, the exception moves to the enclosing block.
RAISE has three forms:
| Form | Where it is legal | What it does |
|---|---|---|
| `RAISE exception_name;` | Anywhere in executable code or a handler | Raises a user-defined or predefined exception by name |
| `RAISE package.exception_name;` | Anywhere | Raises an exception declared in a package |
| `RAISE;` | Only inside an exception handler | Re-raises the exception currently being handled |
Raising a user-defined exception
Declare the exception in the declaration section, then raise it when your own business rule is violated. Oracle cannot detect that kind of violation.
DECLARE
e_low_salary EXCEPTION;
l_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO l_salary
FROM employees
WHERE employee_id = 100;
IF l_salary < 30000 THEN
RAISE e_low_salary;
END IF;
DBMS_OUTPUT.PUT_LINE('Salary OK: ' || l_salary);
EXCEPTION
WHEN e_low_salary THEN
DBMS_OUTPUT.PUT_LINE('Salary is below the minimum');
END;
/In the HR sample data, employee 100 earns 24000, so the handler runs and the "Salary OK" line never prints.
If you remove the WHEN e_low_salary handler, the exception leaves the block unhandled. The caller then receives ORA-06510: PL/SQL: unhandled user-defined exception. For a user-defined exception with no pragma, SQLCODE is 1 and SQLERRM returns User-Defined Exception. Callers cannot tell your exceptions apart by code, which is the main reason to use RAISE_APPLICATION_ERROR or PRAGMA EXCEPTION_INIT for errors that leave the block.
Raising a predefined exception
You can raise predefined exceptions yourself. The exception then behaves exactly as if Oracle had raised it, including its SQLCODE.
BEGIN
UPDATE employees
SET department_id = 50
WHERE employee_id = 9999;
IF SQL%NOTFOUND THEN
RAISE NO_DATA_FOUND;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('SQLCODE is ' || SQLCODE);
END;
/The output is SQLCODE is 100. An UPDATE that matches no rows does not raise NO_DATA_FOUND by itself. Only SELECT INTO and a few other constructs do. Raising it manually is a common way to give an UPDATE the same failure behavior as a query.
Sharing exceptions through a package
An exception declared inside one block is visible only in that block and the blocks nested in it. If callers must handle your exception by name, declare it in a package specification.
CREATE OR REPLACE PACKAGE emp_errors IS
e_employee_missing EXCEPTION;
PRAGMA EXCEPTION_INIT(e_employee_missing, -20010);
END emp_errors;
/
CREATE OR REPLACE FUNCTION get_emp_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
RAISE emp_errors.e_employee_missing;
END get_emp_name;
/
BEGIN
DBMS_OUTPUT.PUT_LINE(get_emp_name(9999));
EXCEPTION
WHEN emp_errors.e_employee_missing THEN
DBMS_OUTPUT.PUT_LINE('Caller handled it, SQLCODE ' || SQLCODE);
END;
/The function translates a low-level exception (NO_DATA_FOUND) into one with domain meaning (e_employee_missing). Callers depend on the package contract and not on how the function finds the employee. The pragma gives the exception the code -20010, so code outside PL/SQL, such as a Java client, sees a stable error number. Oracle supplies no message text for that code. If clients need a message, use RAISE_APPLICATION_ERROR instead.
Re-raising with a bare RAISE
A handler often needs to do some work and then let the error continue to the caller. Typical work is rolling back to a savepoint, releasing a resource, or logging. A handler that does the work and then ends normally swallows the error. The caller sees success even though the operation failed.
A bare RAISE; inside a handler fixes this by raising the same exception again.
CREATE OR REPLACE PROCEDURE move_to_dept (
p_emp_id IN employees.employee_id%TYPE,
p_dept_id IN departments.department_id%TYPE
) IS
BEGIN
SAVEPOINT before_move;
UPDATE employees
SET department_id = p_dept_id
WHERE employee_id = p_emp_id;
IF SQL%NOTFOUND THEN
RAISE NO_DATA_FOUND;
END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO before_move;
DBMS_OUTPUT.PUT_LINE('move_to_dept failed: ' || SQLERRM);
RAISE;
END move_to_dept;
/Calling move_to_dept(100, 999) violates the foreign key to departments. The handler undoes the procedure's own work, prints a message, and re-raises. The caller still receives ORA-02291, so it can decide what to do next.
The flow looks like this:
RAISE versus RAISE exception_name inside a handler
Inside a handler, RAISE; and RAISE name; look similar, but they behave differently.
RAISE;re-raises the exception exactly as it occurred. This keeps the original error code and message.RAISE e_other;raises a new exception. Use this when you intend to translate the error, asget_emp_namedoes.- Naming the same exception again, such as
RAISE NO_DATA_FOUND;, raises a new occurrence of it. Oracle's own message text and the original error details are not carried over. Prefer the bare form when you only want to pass the error along.
The bare form is also the only way to re-raise inside WHEN OTHERS. In that handler you do not know which exception you caught, so you cannot name it.
RAISE outside a handler
A bare RAISE; is legal only while an exception is being handled. Elsewhere the block fails to compile with PLS-00367: a RAISE statement with no exception name must be inside an exception handler. A bare RAISE; inside a nested block that sits within a handler is allowed, and it re-raises the exception the outer handler is handling.
Capture details before you re-raise
If you need the error stack or backtrace for a log, read them inside the handler, before the RAISE;. The functions SQLCODE, SQLERRM, and DBMS_UTILITY.FORMAT_ERROR_BACKTRACE describe the most recent exception. Cleanup code that runs earlier in the handler can raise and handle its own exceptions, which may change what they report. Save the values into local variables first.
DECLARE
l_code NUMBER;
l_msg VARCHAR2(4000);
BEGIN
UPDATE employees SET salary = salary / 0 WHERE employee_id = 100;
EXCEPTION
WHEN OTHERS THEN
l_code := SQLCODE;
l_msg := SQLERRM;
DBMS_OUTPUT.PUT_LINE('Caught ' || l_code || ': ' || l_msg);
RAISE;
END;
/This block ends with an unhandled ORA-01476: divisor is equal to zero. That is the intended result, because RAISE; sent the original error to the caller.
Exceptions raised inside a handler
A handler's own RAISE is not caught by the other WHEN clauses of the same EXCEPTION section. It goes straight to the enclosing block, and in a standalone block that means the caller. This is how re-raising works, but it also means you cannot chain two handlers in one block. If a handler must do risky work and recover from failure, wrap that work in its own inner BEGIN ... EXCEPTION ... END block.
Common mistakes
- Handling an exception and not re-raising it, so the caller thinks the operation worked.
- Writing
WHEN OTHERS THEN NULL;. This hides every error, including ones you never planned for. - Using
RAISE;before logging, then wondering why the log line never appears. Code afterRAISE;in the same handler does not run. - Raising a block-local exception and expecting a caller to handle it by name. Declare it in a package, or use
RAISE_APPLICATION_ERROR. - Relying on
SQLCODEof a user-defined exception without a pragma. It is always 1.
Exercise
A procedure contains EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('failed: ' || SQLERRM);. The calling block wraps the call in its own WHEN OTHERS handler that rolls back. The caller's rollback never runs when the procedure fails. Why, and what is the smallest change that fixes it?
Show answer
The procedure's handler finishes normally, so the exception is swallowed and the caller sees a successful call. Add a bare RAISE; as the last statement of the handler, after the PUT_LINE. The original exception then reaches the caller's handler.
Exercise
What happens when this block runs, and why? BEGIN RAISE; END;
Show answer
It does not compile. A bare RAISE; is only allowed inside an exception handler, so Oracle reports PLS-00367: a RAISE statement with no exception name must be inside an exception handler.