Sub topic 7
Naming Oracle Errors with `PRAGMA EXCEPTION_INIT`
Assume you know basic SQL, PL/SQL block structure, variables, procedures, and transaction control. This chapter focuses on errors that Oracle raises with specific error numbers, such as ORA-02292.
Why name an Oracle error?
Oracle raises many errors during SQL operations. A foreign key constraint can prevent a parent row from being deleted. Without a name for that error, you might write a broad WHEN OTHERS handler and inspect SQLCODE.
PRAGMA EXCEPTION_INIT gives a declared exception a specific Oracle error number. Your handler can then use a meaningful name.
The syntax is:
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(exception_name, -oracle_error_number);The error number must be negative. For example, ORA-02292 has the error number -2292.
| Part | Meaning |
|---|---|
| `e_child_exists` | Your local exception name |
| `EXCEPTION` | Declares an exception variable |
| `PRAGMA EXCEPTION_INIT` | Associates the name with an Oracle error |
| `-2292` | Oracle's numeric code for `ORA-02292` |
A worked example
Suppose a department has employees or other dependent rows. Deleting the department can raise ORA-02292, which means that a child record exists.
DECLARE
e_child_exists EXCEPTION;
PRAGMA EXCEPTION_INIT(e_child_exists, -2292);
BEGIN
DELETE FROM departments
WHERE department_id = 50;
DBMS_OUTPUT.PUT_LINE('Department deleted');
EXCEPTION
WHEN e_child_exists THEN
DBMS_OUTPUT.PUT_LINE(
'Department still has dependent rows'
);
END;
/The PRAGMA is a compiler directive. It tells PL/SQL that e_child_exists represents error -2292. When the DELETE raises that error, control moves to the matching WHEN clause.
The exception name has block scope. If you declare it in an anonymous block, another block cannot use that name. Declare the exception in each procedure that needs it, or expose a shared exception from a package when several procedures use the same business rule.
Choosing between a name and `SQLCODE`
Use PRAGMA EXCEPTION_INIT when a particular Oracle error has a known meaning in your code. The named handler documents that meaning directly.
Use SQLCODE when you need to inspect an error dynamically, especially in general logging code. A named handler is usually clearer than comparing numeric values inside WHEN OTHERS.
Combining named and general handlers
A block can contain several handlers. Oracle checks them for a match. Put specific handlers such as WHEN e_child_exists alongside a final WHEN OTHERS.
Do not use WHEN OTHERS to silently ignore failures. If you cannot resolve the error there, record useful diagnostics and use RAISE to pass the original error to the caller.
Exercise
What does PRAGMA EXCEPTION_INIT(e_child_exists, -2292) do?
Show answer
It associates the declared exception e_child_exists with Oracle error ORA-02292, allowing a WHEN e_child_exists handler to catch that error by name.