Sub topic 6
Declaring your own exceptions
Predefined exceptions such as NO_DATA_FOUND cover errors that Oracle detects. They don't cover rules that belong to your application, such as "an order can't exceed available stock". For those rules you declare an exception, raise it when the rule is broken, and handle it by name.
This chapter assumes you can write a PL/SQL block with a DECLARE, BEGIN and EXCEPTION section. It also assumes you know how WHEN clauses select a handler and how RAISE works at a basic level. The examples use the HR sample schema.
What a user-defined exception is
A user-defined exception is a name you declare in the declaration section of a block, using the type keyword EXCEPTION:
e_invalid_salary EXCEPTION;The declaration does nothing by itself. Oracle never raises this exception on its own. It fires only when your code runs RAISE e_invalid_salary;. After that it behaves like any other exception: control leaves the current statement and goes to the matching handler.
The e_ prefix is a naming convention, not a requirement. It makes exception names easy to tell apart from variables.
Declare, raise, handle
The three steps fit together in one block:
DECLARE
e_salary_too_high EXCEPTION;
l_salary employees.salary%TYPE;
c_limit CONSTANT NUMBER := 20000;
BEGIN
SELECT salary
INTO l_salary
FROM employees
WHERE employee_id = 100;
IF l_salary > c_limit THEN
RAISE e_salary_too_high;
END IF;
DBMS_OUTPUT.PUT_LINE('Salary is within the limit');
EXCEPTION
WHEN e_salary_too_high THEN
DBMS_OUTPUT.PUT_LINE('Salary ' || l_salary || ' exceeds ' || c_limit);
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No such employee');
END;
/When RAISE e_salary_too_high runs, the rest of the BEGIN section is skipped. Control does not return to the statement after RAISE, even though the handler has dealt with the problem. When the handler finishes, the block ends normally.
Predefined and user-defined handlers can sit side by side in the same EXCEPTION section, as above.
What Oracle reports for an unhandled exception
If nothing handles a user-defined exception, it reaches the caller. Oracle has no error number or message for it, because you made the name up. The caller sees a generic error:
DECLARE
e_not_handled EXCEPTION;
BEGIN
RAISE e_not_handled;
END;
/ORA-06510: PL/SQL: unhandled user-defined exceptionThe name e_not_handled is not in the message. A client such as a Java or Python program can't tell which rule failed, so it can't react to the specific error. Two later chapters fix this. PRAGMA EXCEPTION_INIT attaches an error number to an exception name. RAISE_APPLICATION_ERROR returns your own number and message. For now, remember that a bare RAISE of a user-defined exception is best handled inside PL/SQL.
You can see what a WHEN OTHERS handler receives:
BEGIN
DECLARE
e_local EXCEPTION;
BEGIN
RAISE e_local;
END;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
END;
/The output is SQLCODE: 1 and SQLERRM: User-Defined Exception. Oracle assigns every user-defined exception the code +1 (a positive number, unlike most Oracle errors) and the same message text. Because all of your user-defined exceptions share these values, you can't tell them apart with SQLCODE. You have to handle them by name.
Scope rules
An exception name follows the same scope rules as a variable. It is visible in the block where it is declared and in every block nested inside it. It is not visible outside that block.
This matters in the previous example. The outer block can't write WHEN e_local, because e_local is declared in the inner block. The compiler would reject the name with a PLS-00201 error. The outer block can catch the exception only with WHEN OTHERS, as shown above, and the name is lost.
If you want an enclosing block to handle an exception by name, declare it in the enclosing block, or higher.
Shadowing
You can declare an exception in an inner block with the same name as one in an outer block. The inner declaration hides the outer one inside that block. Two exceptions then exist under one name, and a handler matches only the one visible to it.
DECLARE
e_problem EXCEPTION;
BEGIN
DECLARE
e_problem EXCEPTION; -- a different exception with the same name
BEGIN
RAISE e_problem; -- raises the inner one
END;
EXCEPTION
WHEN e_problem THEN -- refers to the outer one, so it does not match
DBMS_OUTPUT.PUT_LINE('Outer handler');
END;
/This block ends with ORA-06510, because the outer handler is for a different exception. Avoid reusing names across nested blocks.
Sharing exceptions across subprograms
An exception declared inside a procedure can't be seen by its callers. When several subprograms must signal the same condition, declare the exception in a package specification. Anything that can call the package can then refer to it as package_name.exception_name.
CREATE OR REPLACE PACKAGE app_errors AS
e_inventory_short EXCEPTION;
END app_errors;
/
CREATE OR REPLACE PROCEDURE reserve_stock (
p_available IN NUMBER,
p_requested IN NUMBER
) IS
BEGIN
IF p_requested > p_available THEN
RAISE app_errors.e_inventory_short;
END IF;
DBMS_OUTPUT.PUT_LINE('Reserved ' || p_requested);
END reserve_stock;
/
BEGIN
reserve_stock(10, 25);
EXCEPTION
WHEN app_errors.e_inventory_short THEN
DBMS_OUTPUT.PUT_LINE('Not enough stock, order held');
END;
/The exception travels from reserve_stock up to the calling block, because the procedure has no handler for it. The caller matches it by its qualified name. If the declaration were local to the procedure, the caller could use only WHEN OTHERS.
A package-level declaration gives you one definition of each application rule that every module shares. It is also the usual place to attach error numbers later.
Limits of the EXCEPTION type
An exception is not a data type in the ordinary sense. Keep these restrictions in mind:
| You might try | Result |
|---|---|
| Assign one exception to another | Not allowed. |
| Pass an exception as a parameter | Not allowed. |
| Store it in a variable or table column | Not allowed. |
| Declare it with an initial value | Not allowed. |
| Use it in an expression | Not allowed. It appears only in `RAISE` and `WHEN`. |
If you need to remember which error occurred, store SQLCODE or a text label in a normal variable.
Choosing between raising styles
| Need | Use |
|---|---|
| Signal a rule inside PL/SQL that other PL/SQL code handles by name | A declared exception and `RAISE` |
| Give a client application a specific error number and message | `RAISE_APPLICATION_ERROR` (a later chapter) |
| Treat an Oracle error you already know as a named case | `PRAGMA EXCEPTION_INIT` (the next chapter) |
Exercise
A procedure declares e_bad_input EXCEPTION; locally and raises it with RAISE e_bad_input; but has no handler for it. A caller wraps the call in a block with WHEN e_bad_input. Does that handler run? What does the caller get if it has only WHEN OTHERS?
Show answer
No. The caller can't see the procedure's local declaration, so WHEN e_bad_input in the caller doesn't compile (PLS-00201). With WHEN OTHERS, the caller catches the exception with SQLCODE of 1 and SQLERRM of User-Defined Exception. The exception's name is lost. To catch it by name, declare it in a package specification and refer to it as package_name.e_bad_input.
Exercise
Write a block that declares e_empty_dept, counts the employees in department 270 with SELECT COUNT(*) INTO, raises e_empty_dept when the count is 0, and prints a message in a handler.
Show answer
DECLARE eemptydept EXCEPTION; lcount NUMBER; BEGIN SELECT COUNT(*) INTO lcount FROM employees WHERE departmentid = 270; IF lcount = 0 THEN RAISE eemptydept; END IF; DBMSOUTPUT.PUTLINE(lcount || ' employees'); EXCEPTION WHEN eemptydept THEN DBMSOUTPUT.PUTLINE('Department 270 has no employees'); END; followed by / on its own line. COUNT(*) always returns one row, so NODATA_FOUND can't occur here, which is why the empty case needs a user-defined exception.