Sub topic 8
Handling `CASE_NOT_FOUND`
This chapter assumes you know anonymous PL/SQL blocks, variables, IF statements, and basic exception handling. CASE_NOT_FOUND is a predefined PL/SQL exception. It occurs when a CASE statement has no matching WHEN branch and no ELSE branch.
Why `CASE_NOT_FOUND` occurs
A simple CASE statement compares one selector value with several possible values:
CASE l_code
WHEN 'A' THEN ...
WHEN 'I' THEN ...
END CASE;If l_code is neither 'A' nor 'I', PL/SQL has no statement to execute. Because there is no ELSE, PL/SQL raises CASE_NOT_FOUND.
The exception is raised when execution reaches the end of the CASE statement without selecting a branch.
Preventing the exception with `ELSE`
Usually, an ELSE branch is the clearest solution. It defines what should happen for unexpected or newly added values.
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');
ELSE
DBMS_OUTPUT.PUT_LINE('Unknown code: ' || l_code);
END CASE;
END;
/This block prints Unknown code: X instead of raising an exception.
An ELSE branch can also assign a safe default, record a warning, or call an error-handling procedure. Choose behavior that matches the business rule. Do not silently treat invalid data as valid data.
Handling `CASE_NOT_FOUND` explicitly
Sometimes an unmatched value is an exceptional condition. In that case, omit ELSE deliberately and handle CASE_NOT_FOUND in the exception section.
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(
'Unsupported status code: ' || l_code
);
END;
/The exception handler catches only this predefined exception. The block prints Unsupported status code: X.
Use this pattern when the caller must know that the value was not recognized. If the handler cannot recover meaningfully, you can raise another error after logging context:
EXCEPTION
WHEN CASE_NOT_FOUND THEN
RAISE_APPLICATION_ERROR(
-20001,
'Unsupported status code: ' || l_code
);Choosing between `ELSE` and an exception
Use ELSE when an unmatched value is expected and the block has a normal fallback. Handle CASE_NOT_FOUND when an unmatched value violates a rule and should follow an error path.
| Situation | Clearer choice |
|---|---|
| Unknown input is valid and has a fallback | `ELSE` |
| Unknown input means invalid data | `CASE_NOT_FOUND` handler or application error |
| Every possible value must be listed | No `ELSE`, with deliberate exception handling |
A CASE statement without ELSE makes the absence of a match visible. That can be useful, but it must be intentional.
Exercise
What happens when l_code contains 'X' and a CASE statement has WHEN 'A' and WHEN 'I', but no ELSE?
Show answer
PL/SQL raises the predefined CASENOTFOUND exception. Add an ELSE branch or handle CASENOTFOUND in the exception section.