Wednesday 19 October 2011

How are exceptions handled in PL/SQL?

PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination.

The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller.

User-Defined Exceptions

PL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example:

ot_failure  EXCEPTION;

In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows:

EXCEPTION

when OT_FAILURE then

out_status_code := g_out_status_code;

out_msg         := g_out_msg;

The following is an example of a subprogram exception:

EXCEPTION

when NO_DATA_FOUND then

g_out_status_code := 'FAIL';

RAISE ot_failure;

Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all user-defined exceptions.

System-Defined Exceptions

Exceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions.

PL/SQL internal exceptions.































































Exception NameOracle Error
CURSOR_ALREADY_OPENORA-06511
DUP_VAL_ON_INDEXORA-00001
INVALID_CURSORORA-01001
INVALID_NUMBERORA-01722
LOGIN_DENIEDORA-01017
NO_DATA_FOUNDORA-01403
NOT_LOGGED_ONORA-01012
PROGRAM_ERRORORA-06501
STORAGE_ERRORORA-06500
TIMEOUT_ON_RESOURCEORA-00051
TOO_MANY_ROWSORA-01422
TRANSACTION_BACKED_OUTORA-00061
VALUE_ERRORORA-06502
ZERO_DIVIDEORA-01476

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established.

1 comment: