Sub topic 8
Raising and re-raising exceptions with RAISE
Assume you know basic PL/SQL blocks, variables, procedures, and exception handlers. This chapter focuses on the RAISE statement. RAISE lets your code signal an exception deliberately or pass an exception to a higher-level block.
Raising a named exception
A user-defined exception is an exception that you declare in the declaration section. Use RAISE with its name when a business rule fails.
DECLARE
e_invalid_limit EXCEPTION;
l_limit NUMBER := -10;
BEGIN
IF l_limit < 0 THEN
RAISE e_invalid_limit;
END IF;
DBMS_OUTPUT.PUT_LINE('Limit accepted');
EXCEPTION
WHEN e_invalid_limit THEN
DBMS_OUTPUT.PUT_LINE('Limit cannot be negative');
END;
/When RAISE e_invalid_limit runs, normal execution stops immediately. PL/SQL searches the current block's EXCEPTION section for a matching WHEN clause. The statement after RAISE is not executed.
You can raise a predefined exception by name as well:
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
IF l_name IS NULL THEN
RAISE NO_DATA_FOUND;
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee was found');
END;
/Usually, Oracle raises predefined exceptions automatically. Explicitly raising one is useful when your own validation should use the same handling path.
Re-raising the current exception
Inside an exception handler, a bare RAISE re-raises the exception currently being handled. This preserves the original error and lets an outer block or the calling program handle it.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Inner block: employee was not found');
RAISE;
END;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Outer block: handling the propagated error');
END;
/The inner handler prints a diagnostic message and then uses RAISE to continue propagation. The outer handler receives the same NO_DATA_FOUND exception. If the inner handler omitted RAISE, execution would continue after the inner block instead.
A bare RAISE has a special meaning. It is valid for re-raising the exception being handled. To raise a specific declared exception, use its name, such as RAISE e_invalid_limit.
Choosing where to handle the error
Handle an exception at the lowest level that has enough information to recover. Re-raise it when the current block can only observe or record the failure. A top-level caller can then decide whether to roll back, show a message, or stop a batch operation.
Exercise
Exercise
What happens if an inner handler prints a message but does not execute RAISE?
Show answer
The exception is considered handled in that block, and control continues after the inner block. An outer handler will not receive that exception.