Sub topic 2
Declaring Your Own Exceptions
Oracle predefined exceptions such as NODATAFOUND cover common failures. Your own business rules often need named errors too. This chapter assumes you know DECLARE blocks, the EXCEPTION section, and WHEN clauses.
Declaring a named exception
Declare an exception like a variable, with the type EXCEPTION:
DECLARE
e_stock_low EXCEPTION;Oracle does not know what estocklow means. Your code must raise it with RAISE and catch it with a WHEN clause.
Naming Oracle errors with PRAGMA EXCEPTION_INIT
Some Oracle errors have no predefined name. PRAGMA EXCEPTION_INIT binds your name to an error number. ORA-02292 means a child row still references the record, so this block names it:
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;
/Raising and re-raising exceptions with RAISE
RAISE estocklow; transfers control to the matching handler in the current block. If no handler matches, the exception passes to the enclosing block.
DECLARE
e_stock_low EXCEPTION;
l_qty NUMBER := 0;
BEGIN
IF l_qty < 1 THEN
RAISE e_stock_low;
END IF;
EXCEPTION
WHEN e_stock_low THEN
DBMS_OUTPUT.PUT_LINE('Stock is too low');
RAISE;
END;
/A bare RAISE inside a handler re-raises the current exception. This example logs the problem, then fails the anonymous block so the caller still sees the error.
Returning custom errors with RAISE_APPLICATION_ERROR
RAISEAPPLICATIONERROR stops the subprogram and returns an error number from -20000 to -20999 with a message to the caller. Use it when the caller must receive a clear error from a procedure.
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;
/Exercise
Exercise
A block declares estocklow and raises it, but no WHEN clause names it. What happens to the exception?
Show answer
It passes to the enclosing block. If no enclosing block handles it, the caller receives an unhandled exception.