Sub topic 8
Handling CASE_NOT_FOUND
This chapter assumes you can write an anonymous PL/SQL block with a DECLARE section and an EXCEPTION section. It also assumes you know the simple and searched CASE statements from the previous chapters. Run the examples with SET SERVEROUTPUT ON in SQL*Plus or SQLcl, or with DBMS_OUTPUT enabled in SQL Developer.
What raises CASE_NOT_FOUND
A CASE statement must run exactly one branch. If no WHEN branch matches and there is no ELSE, PL/SQL has nothing to run, so it raises the predefined exception CASE_NOT_FOUND. Its error number is ORA-06592 and its SQLCODE is -6592.
This differs from IF. An IF-THEN-ELSIF chain with no ELSE does nothing when every condition fails, and the block carries on. A CASE statement treats the missing match as an error.
DECLARE
l_code VARCHAR2(1) := 'X';
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No WHEN branch matched and there is no ELSE');
END;
/The value 'X' matches neither WHEN, so control jumps to the handler. Without the EXCEPTION section, the block would end with ORA-06592: CASE not found while executing CASE statement.
The three outcomes of a missing match
The same situation, "nothing matched and there is no ELSE", has three different results depending on the construct.
| Construct | No match and no ELSE |
|---|---|
| IF-ELSIF chain | Nothing runs. The block continues silently. |
| CASE statement (`END CASE`) | Raises `CASE_NOT_FOUND` (ORA-06592). |
| CASE expression (`END`) | Returns NULL. No exception is raised. |
The CASE expression row is the one that surprises people. An expression must produce a value, and PL/SQL supplies NULL when nothing matches:
DECLARE
l_score NUMBER := 40;
l_label VARCHAR2(10);
BEGIN
l_label := CASE
WHEN l_score >= 90 THEN 'High'
WHEN l_score >= 70 THEN 'Medium'
END;
IF l_label IS NULL THEN
DBMS_OUTPUT.PUT_LINE('No branch matched, so the expression returned NULL');
END IF;
END;
/Because no exception is raised here, an unmatched value can travel on as a NULL. Later code may then fail in a confusing place, or quietly give a wrong answer. Add an ELSE to a CASE expression whenever NULL is not a valid result.
Why the match may fail when you expect it to succeed
Most CASENOTFOUND errors in production come from input you did not plan for. These are the causes to check first.
- An unexpected value. A new status code is added to the data and nobody updates the CASE.
- Case and whitespace.
'a'does not equal'A', and'A 'does not equal'A'for aVARCHAR2comparison. - A NULL selector. A simple CASE compares the selector with each
WHENvalue using equality. NULL is never equal to anything, including NULL, so a NULL selector matches noWHENvalue. - Searched CASE conditions that evaluate to NULL. A
WHENbranch runs only if its condition is TRUE. A condition that is FALSE or NULL is skipped. If every condition is FALSE or NULL, nothing matches.
The NULL selector case deserves a demonstration. A WHEN NULL branch is legal syntax, but it can never run:
DECLARE
l_code VARCHAR2(1) := NULL;
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN NULL THEN DBMS_OUTPUT.PUT_LINE('This line never prints');
ELSE DBMS_OUTPUT.PUT_LINE('ELSE ran: NULL = NULL is not TRUE');
END CASE;
END;
/To handle a NULL selector on purpose, use a searched CASE with IS NULL:
DECLARE
l_code VARCHAR2(1) := NULL;
BEGIN
CASE
WHEN l_code IS NULL THEN DBMS_OUTPUT.PUT_LINE('Code is missing');
WHEN l_code = 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
ELSE DBMS_OUTPUT.PUT_LINE('Other code');
END CASE;
END;
/Put the IS NULL test first. It is the most specific case, and it keeps the later comparisons from ever seeing NULL.
Two ways to deal with it
You have two choices. Either prevent the exception with an ELSE branch, or let it happen and catch it.
Option 1: an ELSE branch
Use ELSE when an unmatched value has a sensible default, such as "Unknown":
DECLARE
l_status VARCHAR2(1) := 'Z';
BEGIN
CASE l_status
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
ELSE DBMS_OUTPUT.PUT_LINE('Unknown status: ' || l_status);
END CASE;
END;
/If an unmatched value means a bug or bad data, an ELSE that prints "Unknown" can hide the problem. In that case, make the ELSE fail on purpose, with a message that says what went wrong:
DECLARE
l_status VARCHAR2(1) := 'Z';
BEGIN
CASE l_status
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
ELSE
RAISE_APPLICATION_ERROR(-20001, 'Unexpected status code: ' || l_status);
END CASE;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Caught: ' || SQLERRM);
END;
/The raised error includes the offending value. The built-in CASE_NOT_FOUND message does not, which makes it harder to diagnose from a log.
Option 2: catch CASE_NOT_FOUND
Omitting ELSE and handling CASE_NOT_FOUND is reasonable when the missing match is rare and you want one handler for the whole block. Name the exception explicitly rather than using WHEN OTHERS, so the handler does not swallow unrelated errors:
DECLARE
l_code VARCHAR2(1) := 'X';
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
END;
/This prints SQLCODE: -6592 and the message ORA-06592: CASE not found while executing CASE statement.
The handler ends the block
An exception handler does not resume the code that failed. When CASE_NOT_FOUND is caught in a block's EXCEPTION section, the handler runs and the block then ends. Any statements after END CASE in that same block are skipped.
If you want to recover and continue, wrap the CASE statement in its own inner block:
DECLARE
l_code VARCHAR2(1) := 'X';
BEGIN
BEGIN
CASE l_code
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Active');
WHEN 'I' THEN DBMS_OUTPUT.PUT_LINE('Inactive');
END CASE;
EXCEPTION
WHEN CASE_NOT_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Unmapped code ' || l_code || ', using default');
END;
DBMS_OUTPUT.PUT_LINE('Processing continues');
END;
/Both messages print, because the inner block handles the exception and finishes normally. The outer block never sees an error.
This matters most inside loops. If a CASE statement sits in a loop body and the exception is handled only outside the loop, the first unmatched row ends the entire loop. To skip bad rows and keep going, put the CASE and its handler in a nested block inside the loop body.
Choosing between ELSE and a handler
Use these criteria to decide.
- If an unmatched value has a reasonable default, use
ELSEwith that default. - If an unmatched value is a data error that must stop the work, use
ELSEwithRAISE_APPLICATION_ERRORand include the value in the message. - If you are matching a closed set of values, such as an enumeration you control, omitting
ELSEis acceptable. The exception then acts as a safety net. - If the CASE is an expression and NULL is not a valid result, always add
ELSE, because there is no exception to catch.
One further point: an ELSE branch also protects you from later changes. Someone may add a value to a column's allowed set without touching your code. A CASE statement with a deliberate ELSE fails with a clear message. A CASE expression without one passes NULL downstream.
Exercise
A block contains this statement: CASE llevel WHEN 1 THEN v := 'Low'; WHEN 2 THEN v := 'High'; END CASE; followed by DBMSOUTPUT.PUTLINE('Done'); in the same block. The block has an EXCEPTION section with WHEN CASENOTFOUND THEN DBMSOUTPUT.PUTLINE('Handled'). What prints when llevel is 3, and how would you make "Done" print as well?
Show answer
Only "Handled" prints. No WHEN matches 3 and there is no ELSE, so CASENOTFOUND is raised. The handler runs and the block ends, so the "Done" line is skipped. To print "Done" too, wrap the CASE statement in an inner BEGIN ... EXCEPTION ... END block that handles CASENOTFOUND, and leave the "Done" line in the outer block. Alternatively, add an ELSE branch to the CASE.
Exercise
A developer writes llabel := CASE lstatus WHEN 'A' THEN 'Active' WHEN 'I' THEN 'Inactive' END; and tests it with lstatus = 'Z', expecting CASENOTFOUND. The test shows no error and llabel is NULL. Why, and what change makes the unexpected value visible?
Show answer
This is a CASE expression (it ends with END, not END CASE), and an expression with no match and no ELSE returns NULL instead of raising an exception. To make the unexpected value visible, add an ELSE that raises an error, for example by calling a procedure that uses RAISEAPPLICATIONERROR, or test l_label IS NULL right after the assignment and raise an error then. Alternatively, rewrite it as a CASE statement with an ELSE that raises the error.