Sub topic 7
Naming Oracle errors with PRAGMA EXCEPTION_INIT
This chapter assumes you can write a PL/SQL block with an EXCEPTION section and WHEN clauses. It also assumes you know the predefined exceptions (NO_DATA_FOUND, TOO_MANY_ROWS) and how to declare a user-defined exception. Familiarity with SQLCODE and SQLERRM helps.
The problem: errors without names
Oracle has thousands of error codes, but PL/SQL predefines names for only about twenty of them. When a statement fails with ORA-02292 (child record found), no predefined exception matches. Without a name, you have two choices:
- Catch the error with
WHEN OTHERSand compareSQLCODEto-2292. - Let the error propagate to the caller.
The first choice produces handlers that catch too much and read poorly. PRAGMA EXCEPTION_INIT offers a third: give the error a name, then handle it like any other exception.
What the pragma does
A pragma is a compiler directive. EXCEPTION_INIT tells the compiler to associate a declared exception name with an Oracle error number.
PRAGMA EXCEPTION_INIT(exception_name, error_code);The rules:
exception_namemust already be declared withEXCEPTIONin the same declarative section, and the pragma must come after that declaration.error_codeis an integer literal. Use a negative number, such as-2292for ORA-02292. The one exception is100, which maps toNO_DATA_FOUND.- The association is made at compile time. Nothing about the pragma runs at execution time.
Here is the pattern from the topic's example, in a form you can run against the HR sample schema:
DECLARE
e_child_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(e_child_exists, -2292);
BEGIN
DELETE FROM departments WHERE department_id = 50;
EXCEPTION
WHEN e_child_exists THEN
DBMS_OUTPUT.PUT_LINE('Department still has dependent rows');
END;
/Department 50 has employees, so the DELETE fails with ORA-02292. Oracle finds that e_child_exists is bound to -2292, so the matching WHEN clause runs. Any other error would not match this handler and would propagate.
Why a named handler beats testing SQLCODE
Compare the two styles for the same situation:
BEGIN
DELETE FROM departments WHERE department_id = 50;
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -2292 THEN
DBMS_OUTPUT.PUT_LINE('Department still has dependent rows');
ELSE
RAISE;
END IF;
END;
/This version works, but it has three weaknesses:
- The magic number
-2292carries no meaning for the reader. - The
ELSE RAISEbranch is easy to forget, and forgetting it silently swallows every other error. - The handler cannot sit next to other named handlers in a single list of
WHENclauses.
With the pragma, the declaration documents the number once, and every handler reads as a sentence.
Common candidates for mapping
| Error | Meaning | Typical name |
|---|---|---|
| ORA-00001 | Unique constraint violated | `DUP_VAL_ON_INDEX` (already predefined) |
| ORA-00054 | Resource busy, `NOWAIT` specified | `e_resource_busy` |
| ORA-00060 | Deadlock detected | `e_deadlock` |
| ORA-00942 | Table or view does not exist | `e_no_table` |
| ORA-01400 | Cannot insert NULL | `e_null_insert` |
| ORA-02291 | Parent key not found | `e_parent_missing` |
| ORA-02292 | Child record found | `e_child_exists` |
Check whether a predefined name already exists before you declare your own. DUP_VAL_ON_INDEX already covers ORA-00001, so mapping it again adds nothing.
Example: dropping a table that may not exist
Dynamic SQL is a good fit, because its errors surface only at run time:
DECLARE
e_no_table EXCEPTION;
PRAGMA EXCEPTION_INIT(e_no_table, -942);
BEGIN
EXECUTE IMMEDIATE 'DROP TABLE temp_results';
EXCEPTION
WHEN e_no_table THEN
NULL; -- table was already gone, which is the state we wanted
END;
/An empty handler is acceptable here because "table is missing" is an expected condition for this block. ORA-00942 also appears when you lack privileges on an existing table, so use this pattern only when you accept that ambiguity.
Naming your own error codes
The pragma also works with application error numbers. RAISE_APPLICATION_ERROR signals numbers in the range -20000 to -20999, and a caller can only test them by number unless you name them. Mapping them in a package specification makes the names shared and reusable:
CREATE OR REPLACE PACKAGE app_errors AS
e_child_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(e_child_exists, -2292);
e_invalid_pct EXCEPTION;
PRAGMA EXCEPTION_INIT(e_invalid_pct, -20001);
END app_errors;
/
CREATE OR REPLACE PROCEDURE check_pct (p_pct IN NUMBER) IS
BEGIN
IF p_pct <= 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Percentage must be positive');
END IF;
END check_pct;
/
BEGIN
check_pct(-5);
EXCEPTION
WHEN app_errors.e_invalid_pct THEN
DBMS_OUTPUT.PUT_LINE('Rejected: ' || SQLERRM);
END;
/The procedure raises error -20001 with its own message. The caller catches it by the name app_errors.e_invalid_pct, and SQLERRM still holds the message text. The number now appears in exactly one place, the package specification.
What changes at run time
A user-defined exception without the pragma reports SQLCODE 1 and the message "User-Defined Exception". If it escapes to a caller that has no handler, the caller sees ORA-06510. Mapping the exception changes this:
SQLCODEreturns the mapped number.SQLERRMreturns the message for that number.- An unhandled mapped exception reaches the caller with its real error code, not ORA-06510.
You can also raise a mapped exception yourself with RAISE e_child_exists;. The raise behaves as though Oracle had signaled the error, with the mapped code.
Scope and placement
The pragma binds a name within its declarative section, so the usual scope rules apply. A name declared in an inner block is visible only in that block. A name declared in a package specification is visible to any code that can see the package.
If you place the pragma before the declaration, in a different declarative section, or with an invalid number, the unit fails to compile. This is a benefit: you find the mistake during development, not in production.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Writing `PRAGMA EXCEPTION_INIT(e, 2292)` with a positive number | Compile error | Use `-2292` |
| Placing the pragma above the `EXCEPTION` declaration | Compile error | Declare first, then the pragma |
| Declaring the exception in a block that cannot be seen by the handler | Handler does not compile | Move the declaration to an enclosing block or a package |
| Reusing `-20001` for unrelated errors | Handlers catch the wrong error | Keep one package of error names |
| Mapping a code that a predefined exception already covers | Redundant, confusing | Use the predefined name |
Summary
PRAGMA EXCEPTION_INIT ties a declared exception name to an Oracle error number at compile time. It turns number checks inside WHEN OTHERS into readable named handlers. It also gives application error numbers a single definition that callers can share through a package.
Exercise
Write a block that tries to insert a row into departments with a manager_id that does not exist in employees, and handles ORA-02291 (parent key not found) with a named exception. Print a short message in the handler.
Show answer
DECLARE eparentmissing EXCEPTION; PRAGMA EXCEPTIONINIT(eparentmissing, -2291); BEGIN INSERT INTO departments (departmentid, departmentname, managerid, locationid) VALUES (999, 'Test', 99999, 1700); EXCEPTION WHEN eparentmissing THEN DBMSOUTPUT.PUT_LINE('Manager does not exist'); END; /
Exercise
A block declares e_busy EXCEPTION; and then PRAGMA EXCEPTION_INIT(e_busy, 54);. It fails to compile. What is wrong, and what is the fix?
Show answer
The error code is positive. Oracle error numbers other than 100 must be negative, so the pragma needs -54 for ORA-00054. Change the line to PRAGMA EXCEPTIONINIT(ebusy, -54);
Exercise
Why is it better to declare a mapped application error such as -20001 in a package specification than in each procedure that raises it?
Show answer
The package gives the number one definition and one name. Callers in other units can catch it as packagename.exceptionname. If each procedure declared its own copy, the names would not be shared, and different procedures could assign the same number to different meanings.