Sub topic 9
Returning custom errors with RAISE_APPLICATION_ERROR
This chapter assumes you can write a PL/SQL block with an EXCEPTION section, declare and raise a user-defined exception, and use RAISE. It also assumes you know how stored procedures are called and how COMMIT and ROLLBACK work.
Why a second way to raise errors
A user-defined exception declared with EXCEPTION and raised with RAISE works well inside PL/SQL. If it reaches a client unhandled, though, the client sees only ORA-06510: PL/SQL: unhandled user-defined exception. That message names no cause. The client also gets no error number it can test.
RAISE_APPLICATION_ERROR fixes this. It raises an exception that carries a number you choose and a message you write. The caller receives both. Java, Python, .NET, SQL*Plus and other PL/SQL code can all read them like any other Oracle error.
Syntax
RAISE_APPLICATION_ERROR(error_code, message [, keep_errors]);| Parameter | Meaning |
|---|---|
| `error_code` | An integer from -20000 to -20999. |
| `message` | Text up to 2048 bytes. Longer text is truncated. |
| `keep_errors` | Optional boolean, default `FALSE`. If `TRUE`, the new error is added to the existing error stack. If `FALSE`, it replaces the stack. |
Oracle reserves every other number for its own errors. A number outside the -20000 to -20999 range raises ORA-21000: error number argument to raise_application_error of ... is out of range.
The procedure can be called from stored subprograms, anonymous blocks, and exception handlers. Use it from a stored subprogram when you want the caller to see the failure.
A worked example
The procedure below validates its input and checks that the UPDATE touched a row. Each check uses its own error number.
CREATE OR REPLACE PROCEDURE raise_salary (
p_emp_id IN employees.employee_id%TYPE,
p_pct IN NUMBER
) IS
BEGIN
IF p_pct <= 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Percentage must be positive');
END IF;
UPDATE employees
SET salary = salary * (1 + p_pct / 100)
WHERE employee_id = p_emp_id;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20002, 'Employee ' || p_emp_id || ' not found');
END IF;
END raise_salary;
/Calling it with a bad percentage from SQL*Plus produces output like this:
ERROR at line 1:
ORA-20001: Percentage must be positive
ORA-06512: at "HR.RAISE_SALARY", line 7
ORA-06512: at line 1The ORA-20001 line is your error. The ORA-06512 lines are the call stack that Oracle adds. They show where the error was raised, and they are a normal part of the output.
What the call does
When RAISE_APPLICATION_ERROR runs, three things happen:
- Execution of the current block stops, as with any raised exception.
- Oracle raises an exception with your number and message. Inside PL/SQL,
SQLCODEreturns the number andSQLERRMreturns the number and message. - The exception propagates up like any other. An enclosing handler can catch it. If none does, it reaches the client.
Any INSERT, UPDATE, or DELETE that the failed subprogram ran is rolled back when the exception leaves it unhandled. This applies to stored subprograms called from a client. The next section explains the scope.
Rollback behavior
For a subprogram called from a client, an unhandled exception undoes the changes made by that call. Oracle sets an implicit savepoint before the call and rolls back to it when the exception leaves the outermost subprogram. Work done before the call stays pending. It is not rolled back or committed, and the caller decides what to do with it.
If you catch the error and handle it, no rollback happens. The changes made before the error remain, and you must decide whether to keep them.
Autonomous transactions are separate. They commit or roll back independently, as a later chapter shows.
Catching a custom error
Callers can catch the error in one of two ways. The first tests SQLCODE in a WHEN OTHERS handler. The second binds a name to the number with PRAGMA EXCEPTION_INIT, the technique from the previous chapter.
DECLARE
e_bad_pct EXCEPTION;
e_no_employee EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bad_pct, -20001);
PRAGMA EXCEPTION_INIT(e_no_employee, -20002);
BEGIN
raise_salary(9999, 10);
EXCEPTION
WHEN e_bad_pct THEN
DBMS_OUTPUT.PUT_LINE('Bad percentage');
WHEN e_no_employee THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
END;
/The named handlers read better than IF SQLCODE = -20002, and the compiler checks the spelling of the names. Because -20002 is a magic number, put the declarations in one place, usually a package specification. Every caller can then share the same names:
CREATE OR REPLACE PACKAGE hr_errors IS
e_bad_pct EXCEPTION;
e_no_employee EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bad_pct, -20001);
PRAGMA EXCEPTION_INIT(e_no_employee, -20002);
END hr_errors;
/A handler can then say WHEN hr_errors.e_no_employee THEN.
Using it inside a handler
You can call RAISE_APPLICATION_ERROR from an exception handler to translate a low-level error into one your application defines. The example below converts a foreign key violation into a message the caller can understand.
CREATE OR REPLACE PROCEDURE delete_department (
p_dept_id IN departments.department_id%TYPE
) IS
e_child_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(e_child_exists, -2292);
BEGIN
DELETE FROM departments WHERE department_id = p_dept_id;
EXCEPTION
WHEN e_child_exists THEN
RAISE_APPLICATION_ERROR(
-20010,
'Department ' || p_dept_id || ' still has employees',
TRUE);
END delete_department;
/Passing TRUE as the third argument keeps ORA-02292 on the stack below ORA-20010. The caller sees both:
ORA-20010: Department 50 still has employees
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated - child record foundWith the default FALSE, the original error disappears and the diagnostic detail is lost. Pass TRUE when you translate an error and want to keep the cause.
Comparing RAISE and RAISE_APPLICATION_ERROR
| Row | `RAISE` with a user-defined exception | `RAISE_APPLICATION_ERROR` |
|---|---|---|
| Error number seen by the client | `ORA-06510` unless you bind a number | The number you chose, -20000 to -20999 |
| Message seen by the client | Generic text | Your text |
| Needs a declaration | Yes | No |
| Can be used outside PL/SQL | Not meaningfully | Yes, clients can test the number |
| Typical use | Control flow inside one unit | Reporting an error to a caller |
A common pattern combines the two. Code inside a package uses RAISE for internal control flow. The public entry points translate failures with RAISE_APPLICATION_ERROR.
Gotchas
- Numbers are shared. Every application in the database uses the same 1,000 numbers. Two packages that both use
-20001for different problems confuse their callers. Agree on ranges, for example -20100 to -20199 for the billing package. - Messages are not translated. Oracle's own messages follow the session language. Your text does not.
- Avoid
SQLERRMin messages you build yourself.SQLERRMincludes theORA-prefix, so the caller sees a doubled prefix and a confusing message. Usekeep_errorsinstead. - Do not catch and discard. A handler that calls
RAISE_APPLICATION_ERRORwithFALSEhides the earlier stack. UseTRUEor log the original error first. - Triggers and functions called from SQL. The call works inside a trigger and is the standard way to block a DML statement with a clear message. A function called from a
SELECTcan raise it too, and the whole statement fails. - Do not call it as a replacement for a return value. Raise an error when the subprogram cannot do its job. An empty result is not an error.
CREATE OR REPLACE TRIGGER trg_emp_salary_check
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < :OLD.salary * 0.5 THEN
RAISE_APPLICATION_ERROR(-20020, 'Salary cannot drop by more than half');
END IF;
END;
/The trigger rejects the offending statement. Oracle rolls back that statement's changes, and the client sees ORA-20020 with your text.
Reading the error in a client
Clients receive the number in a driver-specific field. In Python with python-oracledb, for example:
import oracledb
conn = oracledb.connect(user="hr", password="hr_password", dsn="localhost/freepdb1")
cur = conn.cursor()
try:
cur.callproc("raise_salary", [100, -5])
except oracledb.DatabaseError as exc:
(error,) = exc.args
print(error.code) # 20001
print(error.message) # ORA-20001: Percentage must be positive ...The application can branch on error.code, which is why a stable, documented number matters.
Exercise
A procedure catches ORA-02292 and calls RAISEAPPLICATIONERROR(-20010, 'Department still has employees') with no third argument. A caller needs the original constraint name for debugging. What is wrong, and how do you fix it?
Show answer
The third argument defaults to FALSE, so the new error replaces the error stack and the ORA-02292 text with the constraint name is lost. Pass TRUE as the third argument: RAISEAPPLICATIONERROR(-20010, 'Department still has employees', TRUE). The caller then sees ORA-20010 on top of ORA-02292.
Exercise
What happens if you call RAISEAPPLICATIONERROR(-1403, 'No data')? Why?
Show answer
Oracle raises ORA-21000 because the error number is outside the allowed range of -20000 to -20999. Other numbers are reserved for Oracle's own errors, so you cannot use them with this procedure.
Exercise
Write a handler for the call raise_salary(100, 0) that prints 'Bad percentage' when the procedure raises -20001, without using WHEN OTHERS.
Show answer
DECLARE ebadpct EXCEPTION; PRAGMA EXCEPTIONINIT(ebadpct, -20001); BEGIN raisesalary(100, 0); EXCEPTION WHEN ebadpct THEN DBMSOUTPUT.PUTLINE('Bad percentage'); END; /