Sub topic 3
Handling predefined exceptions such as NO_DATA_FOUND
This chapter assumes you can write a basic PL/SQL block with DECLARE, BEGIN, and EXCEPTION sections. It also assumes you know %TYPE, simple SQL, and how a WHEN clause selects a handler. Here you learn which runtime errors Oracle names for you, how the most common ones are raised, and the mistakes that make them hard to debug.
What a predefined exception is
A predefined exception is an Oracle error that the STANDARD package already declares with a name. You do not declare it, and you do not bind it to an error number. You write WHEN NO_DATA_FOUND THEN and the handler works.
Each predefined exception maps to one ORA error number. Oracle raises them implicitly when a statement fails. You can also raise one yourself with RAISE, which the later chapter on RAISE covers.
| Exception | ORA error | SQLCODE | Typical cause |
|---|---|---|---|
| NO_DATA_FOUND | ORA-01403 | +100 | `SELECT INTO` returns no row, or a read of an uninitialized collection element |
| TOO_MANY_ROWS | ORA-01422 | -1422 | `SELECT INTO` returns more than one row |
| ZERO_DIVIDE | ORA-01476 | -1476 | Division by zero |
| DUP_VAL_ON_INDEX | ORA-00001 | -1 | Insert or update violates a unique constraint |
| INVALID_NUMBER | ORA-01722 | -1722 | A SQL statement converts a non-numeric string to a number |
| VALUE_ERROR | ORA-06502 | -6502 | A PL/SQL conversion, truncation, or size error |
| CURSOR_ALREADY_OPEN | ORA-06511 | -6511 | Opening a cursor that is already open |
| INVALID_CURSOR | ORA-01001 | -1001 | Fetching from or closing a cursor that is not open |
Two details in the table cause confusion. NODATAFOUND has SQLCODE +100, which is the ANSI value, and not -1403. INVALIDNUMBER and VALUEERROR look alike, but INVALIDNUMBER comes from SQL statements and VALUEERROR comes from procedural statements such as an assignment.
NO_DATA_FOUND and TOO_MANY_ROWS
A SELECT ... INTO statement must return exactly one row. Zero rows raise NODATAFOUND. Two or more rows raise TOOMANYROWS. Control leaves the failing statement immediately and goes to the matching WHEN clause.
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 DBMS_OUTPUT.PUT_LINE(l_name) line never runs, because the exception skips the rest of the executable section. After the handler finishes, the block ends. Control does not return to the statement after the SELECT.
Where NO_DATA_FOUND does not appear
NODATAFOUND applies to SELECT INTO and to reads of deleted or uninitialized elements in an index-by table. Other constructs treat "no rows" as normal:
- A cursor
FETCHthat finds no more rows does not raise an exception. You test%NOTFOUNDinstead. UPDATEandDELETEthat touch zero rows do not raise an exception. You testSQL%NOTFOUNDorSQL%ROWCOUNT.- An aggregate query such as
SELECT MAX(salary) INTO ...always returns one row, so it never raises NODATAFOUND. If no rows match, the result isNULL.
The last point is a common source of silent bugs. A handler for NODATAFOUND around SELECT COUNT(*) INTO ... or SELECT MAX(...) INTO ... is dead code.
Handling a missing row as a normal case
A missing row is often not an error. A lookup function may return NULL when nothing matches. Wrap the query in a small block, so the handler stays close to the statement that can fail.
CREATE OR REPLACE FUNCTION get_last_name (
p_emp_id IN employees.employee_id%TYPE
) RETURN employees.last_name%TYPE IS
l_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO l_name
FROM employees
WHERE employee_id = p_emp_id;
RETURN l_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN NULL;
END get_last_name;
/The function returns NULL for an unknown ID and lets TOOMANYROWS propagate. That choice is deliberate. A missing row is an expected outcome, but duplicates in a column that should be unique indicate corrupt data, and the caller should see that failure.
Other predefined exceptions in practice
ZERO_DIVIDE
DECLARE
l_total NUMBER := 500;
l_count NUMBER := 0;
l_avg NUMBER;
BEGIN
l_avg := l_total / l_count;
EXCEPTION
WHEN ZERO_DIVIDE THEN
l_avg := NULL;
DBMS_OUTPUT.PUT_LINE('Count was zero, average set to NULL');
END;
/DUP_VAL_ON_INDEX
This exception is raised when an INSERT or UPDATE would create a duplicate value in a column covered by a unique index or primary key constraint. The row is not written.
BEGIN
INSERT INTO departments (department_id, department_name)
VALUES (10, 'Duplicate test');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
DBMS_OUTPUT.PUT_LINE('That department ID already exists');
END;
/VALUE_ERROR and INVALID_NUMBER
DECLARE
l_small VARCHAR2(3);
BEGIN
l_small := 'too long for this variable';
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('Value does not fit the variable');
END;
/Assigning a string that is too long to a VARCHAR2(3) variable is a procedural error, so it raises VALUEERROR. In contrast, `WHERE employeeid = 'abc'` in a SQL statement raises INVALID_NUMBER, because the conversion happens inside the SQL engine.
Combining handlers
Several exceptions can share one handler with OR. Oracle checks the WHEN clauses from top to bottom and runs the first one that matches. Only one handler runs for a given exception.
DECLARE
l_salary employees.salary%TYPE;
BEGIN
SELECT salary
INTO l_salary
FROM employees
WHERE last_name = 'King';
DBMS_OUTPUT.PUT_LINE(l_salary);
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('Expected exactly one employee named King');
END;
/Use a shared handler only when the response really is the same. If the two cases need different actions, give each its own clause.
Common mistakes
- Assuming execution resumes after the failing statement. It does not. The block ends after the handler runs, unless the
SELECTsits in an inner block. - Swallowing errors. A handler that only prints a message with
DBMS_OUTPUTlets the caller continue as if nothing failed.DBMS_OUTPUTalso shows nothing in many client tools and in batch jobs. - Using one block for several queries. If three
SELECT INTOstatements share a single NODATAFOUND handler, you cannot tell which one failed. Put each query in its own inner block when the response differs. - Handling NODATAFOUND around an aggregate. As noted above,
MAX,MIN,SUM, andCOUNTwithoutGROUP BYalways return a row. - Comparing SQLCODE with -1403. Inside a handler,
SQLCODEfor NODATAFOUND is +100. Use the exception name, which avoids the mistake. - Testing for rows after the fact. Use
SELECT INTOonly when the row must exist. For optional rows, a cursor loop or a handler in an inner block makes the intent clear.
Exercise
A block runs SELECT MAX(salary) INTO l_max FROM employees WHERE department_id = 999; and department 999 has no employees. Does the block raise NODATAFOUND? What value does l_max hold afterward?
Show answer
No. An aggregate query without GROUP BY always returns exactly one row, so SELECT INTO succeeds. Because no rows match, MAX returns NULL, and l_max is NULL.
Exercise
In the getlastname function above, why does the handler cover NODATAFOUND but leave TOOMANYROWS unhandled?
Show answer
A missing row is an expected result, so returning NULL is a reasonable answer. Several rows for a primary key lookup mean the data is wrong. Letting TOOMANYROWS propagate reports that problem to the caller instead of hiding it.
Exercise
Write a WHEN clause that handles both ZERODIVIDE and VALUEERROR with the same message.
Show answer
WHEN ZERODIVIDE OR VALUEERROR THEN DBMSOUTPUT.PUTLINE('Calculation failed');