Sub topic 1
What happens when a PL/SQL block hits an error
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), the DECLARE, BEGIN, and END structure of a PL/SQL block, and COMMIT and ROLLBACK. You should also be comfortable with variables declared with %TYPE.
What happens when a PL/SQL block hits an error
An exception is a runtime error. When a statement fails, PL/SQL stops running the remaining statements in the BEGIN section and transfers control to the EXCEPTION section. If no WHEN clause matches the error, the error passes to the enclosing block or to the caller.
Writing an EXCEPTION section with WHEN clauses
The EXCEPTION section sits between the BEGIN statements and END. Each WHEN clause names one exception and holds the code to run for it.
BEGIN
NULL;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Row not found');
END;
/Handling predefined exceptions such as NO_DATA_FOUND
A predefined exception is an error that Oracle names for you. NODATAFOUND is raised when a SELECT INTO returns no row. TOOMANYROWS is raised when it returns more than one row.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
DBMS_OUTPUT.PUT_LINE(l_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee with that ID');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('More than one employee matched');
END;
/The DBMSOUTPUT.PUTLINE call after the SELECT never runs when no row matches. Control jumps straight to the NODATAFOUND handler.
Catching everything with WHEN OTHERS
WHEN OTHERS matches any error that no earlier WHEN clause names. Place it last. Because it catches every error, it can hide the real cause. Record the error, then use RAISE to pass it on, unless the handler fully recovers from it.
Reading the error with SQLCODE and SQLERRM
SQLCODE returns the number of the most recent error. For NODATAFOUND, it returns 100. SQLERRM returns the message text, such as "ORA-01403: no data found". Read both only inside a handler.
DECLARE
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
RAISE;
END;
/This block prints both values, then RAISE re-raises the error. The client still receives ORA-01403.
Exercise
In the block above, what does the handler print, and does the block finish successfully? Assume no employee has ID 9999.
Show answer
It prints "SQLCODE: 100" and "SQLERRM: ORA-01403: no data found". The block does not finish successfully, because RAISE passes the error to the caller.