1. What is an Exception?
An exception is an error condition during the execution of a PL/SQL block. When an exception occurs, PL/SQL transfers control to the exception-handling part of the block.
2. Types of Exceptions
A. Predefined Exceptions
Oracle provides predefined exceptions for common errors:
-
NO_DATA_FOUND– Raised when aSELECT INTOreturns no rows. -
TOO_MANY_ROWS– Raised when aSELECT INTOreturns more than one row. -
ZERO_DIVIDE– Raised when attempting to divide by zero. -
VALUE_ERROR– Raised for numeric or conversion errors. -
INVALID_CURSOR– Raised when performing an illegal cursor operation.
B. User-Defined Exceptions
-
Declared by the programmer using the
EXCEPTIONkeyword. -
Raised manually with the
RAISEstatement.
C. Non-Predefined Oracle Errors
-
Some Oracle errors do not have predefined exceptions.
-
You can use
PRAGMA EXCEPTION_INITto associate a specific Oracle error number with a named exception.
3. Exception Handling Structure
A PL/SQL block with exception handling has the structure:
4. Basic Example – Handling a Predefined Exception
Output:
5. Example – Handling NO_DATA_FOUND
6. User-Defined Exception Example
Output:
7. Handling All Exceptions – WHEN OTHERS
WHEN OTHERS catches all exceptions that are not explicitly handled:
8. Key Points
-
Order matters – The first matching exception handler is executed.
-
Avoid using only
WHEN OTHERSas it can mask real issues. Always logSQLCODEandSQLERRM. -
Use
RAISEto propagate exceptions to the caller if needed.
No comments:
Post a Comment