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 INTO
returns no rows. -
TOO_MANY_ROWS
– Raised when aSELECT INTO
returns 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
EXCEPTION
keyword. -
Raised manually with the
RAISE
statement.
C. Non-Predefined Oracle Errors
-
Some Oracle errors do not have predefined exceptions.
-
You can use
PRAGMA EXCEPTION_INIT
to 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 OTHERS
as it can mask real issues. Always logSQLCODE
andSQLERRM
. -
Use
RAISE
to propagate exceptions to the caller if needed.
No comments:
Post a Comment