Sub topic 1
What happens when a PL/SQL block hits an error
Prerequisites
This chapter assumes you can already do the following:
- Write basic SQL:
SELECT,INSERT,UPDATE,DELETE. - Read and write an anonymous PL/SQL block with
DECLARE,BEGINandEND. - Declare variables, including with
%TYPE, and useIFandLOOP. - Call a stored procedure or function.
- Explain what
COMMITandROLLBACKdo.
The examples use the Oracle HR sample schema (the employees table). Run them in SQL*Plus, SQL Developer or SQLcl with SET SERVEROUTPUT ON so that DBMS_OUTPUT text is displayed.
Errors at run time
PL/SQL reports a run-time error as an exception. An exception is a named or numbered error condition that interrupts normal execution. Typical causes are a query that returns no rows, a duplicate key, a division by zero, or a value too large for its variable.
An exception can arise in two ways:
- Implicitly. The PL/SQL runtime or the SQL engine detects the problem. A
SELECT ... INTOthat finds no row raisesNO_DATA_FOUND(ORA-01403) without any code from you. - Explicitly. Your code raises the exception on purpose with
RAISEorRAISE_APPLICATION_ERROR. Later chapters cover both.
Either way, the effect on execution is the same. Normal execution stops at the failing statement, and control moves out of the executable section.
Normal flow versus exceptional flow
A block has up to three sections: declarations, an executable section between BEGIN and EXCEPTION, and an optional exception section. While no error occurs, statements run in order and the exception section is never entered.
When an exception is raised in the executable section, the runtime does the following:
- It abandons the rest of the executable section. Statements after the failing one do not run.
- It looks in the same block's exception section for a handler that matches the exception.
- If it finds one, it runs that handler's statements. The block then ends, and the caller continues as if the block had finished normally.
- If it finds none, it passes the exception to the enclosing block, or to the caller if there is no enclosing block. The search repeats there.
- If no block or caller handles it, the exception reaches the client as an unhandled error.
A first example: the skipped statement
The block below labels each step so you can see which statements run.
SET SERVEROUTPUT ON
DECLARE
l_name employees.last_name%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE('Step 1: before the query');
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
DBMS_OUTPUT.PUT_LINE('Step 2: after the query');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Step 3: handler');
END;
/Employee 9999 does not exist, so the query raises NO_DATA_FOUND. The output is:
Step 1: before the query
Step 3: handler"Step 2" never prints. Control jumped from the SELECT straight to the handler. It did not return to the statement after the SELECT. PL/SQL has no "resume" for a block that has failed.
The same block with no handler
Remove the exception section and run it again.
SET SERVEROUTPUT ON
DECLARE
l_name employees.last_name%TYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE('Step 1: before the query');
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = 9999;
DBMS_OUTPUT.PUT_LINE('Step 2: after the query');
END;
/Now nothing handles the exception. The block ends with an error, and the client shows it:
Step 1: before the query
ORA-01403: no data found
ORA-06512: at line 5ORA-01403 is the error itself. ORA-06512 is the call stack line. It tells you which line of which program unit the error passed through. Here that is the line where the SELECT begins.
Whether an unhandled error stops a larger script depends on the client. SQL*Plus keeps running later commands unless you set WHENEVER SQLERROR EXIT. Application code receives the error as a database exception in its own language.
What happens to the data
An exception does not automatically undo everything the block did. The database guarantees that the single failing SQL statement is atomic. Oracle rolls back the effects of that one statement, and only that statement. Changes made by earlier statements in the same transaction stay in place, and the transaction stays open.
This example shows it. It creates a small table, then inserts the same key twice.
SET SERVEROUTPUT ON
CREATE TABLE demo_keys (id NUMBER PRIMARY KEY);
BEGIN
INSERT INTO demo_keys (id) VALUES (1);
INSERT INTO demo_keys (id) VALUES (1);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('Duplicate key: ' || SQLERRM);
END;
/
SELECT COUNT(*) AS row_count FROM demo_keys;The second INSERT raises DUP_VAL_ON_INDEX (ORA-00001). The handler runs and the block ends normally. The count query then returns 1: the first insert is still there, uncommitted, because the exception did not roll it back.
This has two consequences:
- If a handler swallows an error and the block ends normally, the caller sees success. It may then commit a half-finished set of changes.
- If the exception is unhandled, the caller receives the error. Oracle rolls back the failed statement, but earlier work in the transaction is still pending. The client decides whether to roll back or commit it.
Exceptions and transaction control get a full chapter later. For now, remember that raising an exception moves control and undoes only the failing statement.
DROP TABLE demo_keys;Where a handler can and cannot help
A handler covers only the executable section of its own block. Two places are not covered:
- The declaration section. An error while initializing a variable, such as
l_small VARCHAR2(2) := 'too long';, raises an exception that the same block's handler does not see. It goes to the enclosing block or caller. - The exception section itself. An exception raised inside a handler also goes outward. It is not caught by the other
WHENclauses of the same block.
A later chapter explains both cases. Keep in mind now that "the block has an EXCEPTION section" does not mean "every error in the block is caught."
Where handling happens
An exception section is not a place for general cleanup that must always run. It runs only when an exception occurs. Code that must run in both outcomes needs to be placed after the block, or written once in the normal path and once in the handler.
The runtime also checks handlers in order. It runs the first WHEN clause that matches. If none matches and the block has no WHEN OTHERS, the exception leaves the block. The next chapter covers the syntax of those clauses.
Summary of the flow
- An exception is raised implicitly by the runtime or explicitly by your code.
- The rest of the executable section is skipped.
- The runtime looks for a matching handler in the current block, then in each enclosing block or caller.
- A handled exception ends the block normally. An unhandled one reaches the client.
- Only the failing SQL statement is rolled back. Earlier changes in the transaction remain.
Exercise
A block inserts a row into table T1, then runs a second INSERT that raises DUPVALONINDEX. The block has a handler `WHEN DUPVALONINDEX THEN DBMSOUTPUT.PUTLINE('duplicate'); and no other statements after the second INSERT. The block ends and you immediately run SELECT COUNT(*) FROM T1` in the same session, with no COMMIT or ROLLBACK in between. Is the first row visible, and does the caller see an error?
Show answer
The first row is visible to your session, because the exception rolls back only the failing second INSERT and the transaction is still open with the first INSERT pending. The caller does not see an error, because the handler matched the exception and the block ended normally; the only sign of the problem is the 'duplicate' message. The first row is still uncommitted, so a later ROLLBACK would remove it.
Exercise
In the block below, which lines of output appear, and in what order? BEGIN DBMSOUTPUT.PUTLINE('A'); DBMSOUTPUT.PUTLINE('B' || TONUMBER('x')); DBMSOUTPUT.PUTLINE('C'); EXCEPTION WHEN VALUEERROR THEN DBMSOUTPUT.PUTLINE('D'); END;
Show answer
Only A and D, in that order. Line A prints. The conversion TONUMBER('x') fails while the argument for the second PUTLINE is being evaluated, in a PL/SQL expression, so PL/SQL raises VALUE_ERROR (ORA-06502) and nothing is printed for B. C is skipped because control jumps to the handler, which prints D. The block then ends normally.