Handling Exceptions
Once an exception is raised, the current PL/SQL block stops its regular execution and transfers control to the exception section. The exception is then either handled by an exception handler in the current PL/SQL block or passed to the enclosing block.
To handle or trap an exception once it is raised, you must write an exception handler for that exception. In your code, your exception handlers must appear after all the executable statements in your program but before the END statement of the block. The EXCEPTION keyword indicates the start of the exception section and the individual exception handlers:
DECLARE ...declarations
... BEGIN ...executable statements
... [ EXCEPTION ...exception handlers
... ] END;
The syntax for an exception handler is as follows:
WHENexception_name
[ ORexception_name
... ] THENexecutable statements
or:
WHEN OTHERS
THEN
executable statements
You can have multiple exception handlers in a single exception section. The exception handlers are structured much like a conditional CASE statement, as shown in the following table:
Property | Description |
---|---|
EXCEPTION
WHEN NO_DATA_FOUND
THEN | If the NO_DATA_FOUND exception is raised, then execute the first set of statements. |
WHEN payment_overdue
THEN | If the payment is overdue, then execute the second set of statements. |
WHEN OTHERS
THEN | If any other exception is encountered, then execute the third set of statements. |
An exception is handled ...
Get Oracle PL/SQL Programming, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.