PL/SQL Catch Multiple Exceptions
Use separate WHEN clauses for different errors, or combine related exception names with OR in one handler. Put the most specific handlers first, keep WHEN OTHERS last, and use nested blocks when recovery code can fail independently. This guide shows the common patterns for predefined errors, custom exceptions, dynamic SQL, and bulk DML.
How PL/SQL Exception Matching Works
A PL/SQL block has an executable section followed by an optional EXCEPTION section:
DECLARE
-- Declarations
BEGIN
-- Executable statements
EXCEPTION
-- Exception handlers
END;
/
When an error occurs in the BEGIN section, PL/SQL stops the failing statement and searches the WHEN clauses for the first matching handler. It runs that handler, then continues after the block.
That order matters:
- A specific handler such as
WHEN NO_DATA_FOUNDhandles only that condition. - A combined handler such as
WHEN NO_DATA_FOUND OR TOO_MANY_ROWShandles either condition. WHEN OTHERSmatches any exception not matched earlier.- If no handler matches, the exception propagates to the calling block or stops the program.
An exception handler is a first-match decision list, not a set of handlers that all run.
For example, WHEN OTHERS must be last. The WHEN clauses are searched in order, and the first matching handler runs.
How to Catch Multiple Exceptions in One PL/SQL Block
Use this method when one procedure, function, anonymous block, or loop can raise several errors and each error needs a different response.
Choose the handler structure that matches the action you need to take.
| Situation | Handler Pattern | Best Use |
|---|---|---|
| Each error needs a different action | Separate WHEN clauses |
Log or recover differently for each error |
| Several errors have the same action | One WHEN ... OR ... THEN clause |
Shared fallback, cleanup, or message |
| A database error has no predefined PL/SQL name | PRAGMA EXCEPTION_INIT |
Catch a specific Oracle error number |
Error occurs in EXECUTE IMMEDIATE |
Handler around the dynamic statement | Capture SQL parsing or execution failures |
Some FORALL rows may fail |
SAVE EXCEPTIONS and SQL%BULK_EXCEPTIONS |
Process valid bulk rows and report failures |
Step 1: Identify the Errors You Expect
Start with errors that your code can reasonably recover from or report clearly. Common predefined PL/SQL exceptions include:
NO_DATA_FOUNDfor aSELECT ... INTOthat returns no rowsTOO_MANY_ROWSfor aSELECT ... INTOthat returns more than one rowDUP_VAL_ON_INDEXfor a duplicate unique or primary-key valueZERO_DIVIDEfor division by zeroVALUE_ERRORfor conversion, numeric, or string-size errors
Use WHEN OTHERS only as a final safety net.
Step 2: Declare Custom Exceptions When Needed
Predefined exceptions need no declaration. For application-specific validation, declare your own exception in the declarative section.
DECLARE
e_invalid_status EXCEPTION;
v_status VARCHAR2(20) := 'ARCHIVED';
BEGIN
IF v_status NOT IN ('NEW', 'ACTIVE', 'CLOSED') THEN
RAISE e_invalid_status;
END IF;
DBMS_OUTPUT.PUT_LINE('Status is valid.');
EXCEPTION
WHEN e_invalid_status THEN
DBMS_OUTPUT.PUT_LINE('Status is not allowed.');
END;
/
Use a custom exception when the condition is part of your business logic rather than a database error.
Step 3: Add Specific Handlers Before General Ones
Write a separate WHEN clause for every exception that requires distinct handling.
DECLARE
v_employee_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_employee_name
FROM employees
WHERE employee_id = 9999;
DBMS_OUTPUT.PUT_LINE('Employee: ' || v_employee_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee matched that ID.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('The query returned more than one employee.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(
'Unexpected error ' || SQLCODE || ': ' || SQLERRM
);
RAISE;
END;
/
The RAISE; in the WHEN OTHERS handler re-raises the original exception after logging it. This prevents a serious error from being silently treated as a successful run.
If several exceptions require exactly the same response, combine them with OR:
DECLARE
v_result NUMBER;
BEGIN
v_result := 10 / 0;
EXCEPTION
WHEN ZERO_DIVIDE OR VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('A calculation or conversion failed.');
END;
/
Use combined handlers only when the recovery is genuinely the same. Separate handlers are clearer when the message, logging details, retry behavior, or cleanup differs.
Step 4: Test Both the Handled and Unhandled Paths
Test one input for each expected exception and one successful input. Also test an unexpected failure to confirm that your WHEN OTHERS handler records enough context.
A useful logging handler includes:
DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
For production code, write these values, relevant key values, and a timestamp to an application log or error table instead of relying on DBMS_OUTPUT.
Handling SELECT INTO Errors
A SELECT ... INTO statement expects exactly one row. It raises:
NO_DATA_FOUNDwhen it returns zero rowsTOO_MANY_ROWSwhen it returns more than one row
Oracle TimesTen documents WHEN TOO_MANY_ROWS THEN for a SELECT ... INTO that returns multiple rows; the associated Oracle-style error is ORA-01422: exact fetch returns more than requested number of rows.
DECLARE
v_last_name employees.last_name%TYPE;
BEGIN
SELECT last_name
INTO v_last_name
FROM employees
WHERE first_name = 'John';
DBMS_OUTPUT.PUT_LINE(v_last_name);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No employee named John was found.');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(
'More than one employee named John was found. Use a unique condition or a cursor.'
);
END;
/
Do not use TOO_MANY_ROWS as normal query-control logic when you can prevent the condition. Add a unique predicate, query a unique key, aggregate intentionally, or use a cursor when multiple rows are valid.
Catching Named Oracle and Db2 Errors
Some database errors do not have predefined PL/SQL exception names. You can assign a name to a specific error number with PRAGMA EXCEPTION_INIT.
In Oracle Database, this is commonly used for errors such as a deadlock, a resource-busy error, or a business-relevant constraint failure.
DECLARE
e_deadlock EXCEPTION;
PRAGMA EXCEPTION_INIT(e_deadlock, -60);
BEGIN
-- SQL that might encounter ORA-00060
NULL;
EXCEPTION
WHEN e_deadlock THEN
DBMS_OUTPUT.PUT_LINE('Deadlock detected. Retry or investigate the transaction order.');
END;
/
Place the pragma immediately after the exception declaration.
Db2’s PL/SQL compatibility layer supports Oracle SQLCODE mapping with a declaration such as:
exception2 EXCEPTION;
PRAGMA EXCEPTION_INIT(exception2, -942);
For Db2, the accepted Oracle SQLCODE mappings are product-specific; confirm the exact mapping in IBM’s Oracle-Db2 error mapping documentation. When you need to match a native Db2 SQLSTATE instead, Db2 supports this form immediately after declaring the exception:
exception3 EXCEPTION;
PRAGMA DB2_EXCEPTION_INIT(exception3, '42601');
The SQLSTATE must match the Db2 database error you intend to handle.
Catching Exceptions From EXECUTE IMMEDIATE
EXECUTE IMMEDIATE raises exceptions in the block where it runs. Handle it as you would static SQL, but log the statement or a safe identifier for it because dynamic SQL failures can be harder to diagnose.
DECLARE
v_sql VARCHAR2(1000);
BEGIN
v_sql := 'UPDATE employees SET salary = salary * 1.05 WHERE department_id = :1';
EXECUTE IMMEDIATE v_sql USING 50;
EXCEPTION
WHEN VALUE_ERROR THEN
DBMS_OUTPUT.PUT_LINE('A dynamic SQL value or conversion was invalid.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Dynamic SQL failed: ' || SQLERRM);
DBMS_OUTPUT.PUT_LINE('Statement: ' || v_sql);
RAISE;
END;
/
Avoid concatenating untrusted values into dynamic SQL. Bind values with USING; reserve concatenation for validated SQL identifiers that cannot be bound, such as a table name selected from an approved list.
Use a Nested Block for Risky Recovery Code
A new exception raised inside an exception handler is not caught by another handler in that same block. It can only be handled by an enclosing block.
For example, an error-log insert could fail because the log table is unavailable. An error handler can attempt the log insert as follows:
BEGIN
-- Main application work
RAISE_APPLICATION_ERROR(-20001, 'Main operation failed.');
EXCEPTION
WHEN OTHERS THEN
BEGIN
INSERT INTO error_log (
error_code,
error_message,
logged_at
)
VALUES (
SQLCODE,
SQLERRM,
SYSTIMESTAMP
);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
NULL;
END;
RAISE;
END;
/
The NULL handler applies only to a failed log insert. Use this sparingly: the empty handler is limited to a failed log insert.
Handling Multiple Errors in FORALL Bulk DML
Regular PL/SQL stops bulk DML at the first failing iteration. Add SAVE EXCEPTIONS to a FORALL statement when you want Oracle to attempt the remaining iterations and report all failures afterward.
DECLARE
TYPE t_employee_ids IS TABLE OF employees.employee_id%TYPE;
l_employee_ids t_employee_ids := t_employee_ids(100, 101, 102, 103);
e_bulk_errors EXCEPTION;
PRAGMA EXCEPTION_INIT(e_bulk_errors, -24381);
l_error_count PLS_INTEGER;
BEGIN
FORALL i IN 1 .. l_employee_ids.COUNT SAVE EXCEPTIONS
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = l_employee_ids(i);
EXCEPTION
WHEN e_bulk_errors THEN
l_error_count := SQL%BULK_EXCEPTIONS.COUNT;
DBMS_OUTPUT.PUT_LINE(
'Failed bulk iterations: ' || l_error_count
);
FOR i IN 1 .. l_error_count LOOP
DBMS_OUTPUT.PUT_LINE(
'Iteration ' || SQL%BULK_EXCEPTIONS(i).ERROR_INDEX ||
' failed with: ' ||
SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE)
);
END LOOP;
END;
/
SQL%BULK_EXCEPTIONS.COUNT gives the number of failed FORALL iterations after bulk processing and before you loop through the failures. ERROR_INDEX identifies the failing iteration, while ERROR_CODE identifies the database error.
Treat the exception list as a report that still needs action. You may need to correct invalid input, record the failed keys, retry transient failures, or roll back the broader transaction depending on your application’s transaction rules.
Confirm Your Exception Handling Is Safe
Before relying on exception handling in a procedure or package, check the following:
- Specific exception handlers appear before
WHEN OTHERS. - Every handled error has a clear recovery, message, or re-raise decision.
- Dynamic SQL uses bind variables for values.
SELECT ... INTOqueries are expected to return exactly one row.- Bulk DML processes
SQL%BULK_EXCEPTIONSafterSAVE EXCEPTIONS. - Tests cover successful execution, each expected exception, and an unexpected exception.
Predefined, non-predefined, and application-defined exceptions are all handled through the same EXCEPTION section structure, as outlined in Oracle’s PL/SQL exception documentation. The important part is deciding which failures are recoverable and allowing all others to remain visible.
Frequently Asked Questions
Can PL/SQL catch multiple exceptions in one WHEN clause?
Yes. Use OR between exception names when they should receive the same treatment.
EXCEPTION
WHEN NO_DATA_FOUND OR TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('The query did not return exactly one row.');
END;
/
Use separate WHEN clauses if each exception needs different logging, recovery, or user-facing text.
How do you handle exceptions in PL/SQL?
Put an EXCEPTION section after the executable statements in a PL/SQL block. Add specific WHEN exception_name THEN handlers first, then add WHEN OTHERS THEN last only if you need a fallback handler.
For unexpected errors, log SQLCODE and SQLERRM, then use RAISE; to preserve the original failure.
Does WHEN OTHERS catch every PL/SQL exception?
WHEN OTHERS catches every exception that was not matched by an earlier handler in the same block. It does not make later handlers run, so it must be the final clause.
If code inside its handler fails, that new exception needs a surrounding block’s EXCEPTION section to catch it.
How do I catch an error from EXECUTE IMMEDIATE?
Place EXECUTE IMMEDIATE inside a BEGIN ... EXCEPTION ... END block and handle the relevant predefined or named exceptions there. A final WHEN OTHERS handler can log SQLERRM and the dynamic SQL text before re-raising the error.
Use USING for bind values so values do not become part of the SQL string.
How do I handle multiple errors during FORALL?
Use FORALL ... SAVE EXCEPTIONS, catch the bulk DML exception associated with -24381, and inspect SQL%BULK_EXCEPTIONS. SQL%BULK_EXCEPTIONS.COUNT gives the number of failed iterations, and each entry supplies an iteration index and error code.
This lets successful iterations complete while your code identifies and handles rows that failed.
