Skip Headers
Oracle® Database PL/SQL Language Reference
11g Release 2 (11.2)

Part Number E10472-02
Go to Documentation Home
Home
Go to Book List
Book List
Go to Table of Contents
Contents
Go to Index
Index
Go to Master Index
Master Index
Go to Feedback page
Contact Us

Go to previous page
Previous
Go to next page
Next
View PDF

11 PL/SQL Error Handling

This chapter explains how to handle PL/SQL compile-time warnings and PL/SQL run-time errors. The latter are called exceptions.

Topics:

Tip:

If you have problems creating or running PL/SQL code, check the Oracle Database trace files. The USER_DUMP_DEST initialization parameter specifies the current location of the trace files. You can find the value of this parameter by issuing SHOW PARAMETER USER_DUMP_DEST. For more information about trace files, see Oracle Database Performance Tuning Guide.

Compile-Time Warnings

While compiling stored PL/SQL units, the PL/SQL compiler generates warnings for conditions that are not serious enough to produce errors and prevent compilation—for example, using a compiler parameter or language feature that is deprecated.

To see warnings (and errors) generated during compilation, either use the SQL*Plus command SHOW ERRORS or query the static data dictionary view *_ERRORS. For information about the view, see Oracle Database Reference.

The message code of a PL/SQL warning has the form PLW-nnnnn. For the message codes of all PL/SQL warnings, see Oracle Database Error Messages.

Table 11-1 summarizes the categories of warnings.

Table 11-1 Compile-Time Warning Categories

Category Description Example

SEVERE

Condition might cause unexpected action or wrong results.

Aliasing problems with parameters

PERFORMANCE

Condition might cause performance problems.

Passing a VARCHAR2 value to a NUMBER column in an INSERT statement

INFORMATIONAL

Condition does not affect performance or correctness, but you might want to change it to make the code more maintainable.

Code that can never run


By setting the compilation parameter PLSQL_WARNINGS, you can:

You can set the value of PLSQL_WARNINGS for:

In any of the preceding ALTER statements, you set the value of PLSQL_WARNINGS with this syntax:

PLSQL_WARNINGS = 'value_clause' [, 'value_clause' ] ...

For the syntax of value_clause, see Oracle Database Reference.

Example 11-1 shows several ALTER statements that set the value of PLSQL_WARNINGS.

Example 11-1 Setting Value of PLSQL_WARNINGS Compilation Parameter

For the session, enable all warnings—highly recommended during development:

ALTER SESSION SET PLSQL_WARNINGS='ENABLE:ALL';

For the session, enable PERFORMANCE warnings:

ALTER SESSION SET PLSQL_WARNINGS='ENABLE:PERFORMANCE';

For the procedure loc_var, enable PERFORMANCE warnings, and reuse settings:

ALTER PROCEDURE loc_var
  COMPILE PLSQL_WARNINGS='ENABLE:PERFORMANCE'
  REUSE SETTINGS;

For the session, enable SEVERE warnings, disable PERFORMANCE warnings, and treat PLW-06002 warnings as errors:

ALTER SESSION
  SET PLSQL_WARNINGS='ENABLE:SEVERE', 'DISABLE:PERFORMANCE', 'ERROR:06002';

For the session, disable all warnings:

ALTER SESSION SET PLSQL_WARNINGS='DISABLE:ALL';

To display the current value of PLSQL_WARNINGS, query the static data dictionary view ALL_PLSQL_OBJECT_SETTINGS. For information about this view, see Oracle Database Reference.

DBMS_WARNING Package

If you are writing PL/SQL subprograms in a development environment that compiles them, you can control PL/SQL compile-time warning messages by invoking subprograms in the DBMS_WARNING package. You can also use this package when compiling a complex application, composed of several nested SQL*Plus scripts, where different warning settings apply to different subprograms. You can save the current state of the PLSQL_WARNINGS parameter with one call to the package, change the parameter to compile a particular set of subprograms, then restore the original parameter value.

Unreachable code could represent a mistake or be intentionally hidden by a debug flag, so you might want a warning message for it.

The procedure in Example 11-2 is unreachable.

Example 11-2 DBMS_WARNING Package

Disable all warning messages for this session:

ALTER SESSION SET PLSQL_WARNINGS='DISABLE:ALL';

With warnings disabled, this procedure compiles with no warnings:

CREATE OR REPLACE PROCEDURE unreachable_code AS
  x CONSTANT BOOLEAN := TRUE;
BEGIN
  IF x THEN
    DBMS_OUTPUT.PUT_LINE('TRUE');
  ELSE
    DBMS_OUTPUT.PUT_LINE('FALSE');
  END IF;
END unreachable_code;
/

Enable all warning messages for this session:

CALL DBMS_WARNING.set_warning_setting_string ('ENABLE:ALL' ,'SESSION');

Check warning setting:

SELECT DBMS_WARNING.get_warning_setting_string() FROM DUAL;

Result:

DBMS_WARNING.GET_WARNING_SETTING_STRING()
-----------------------------------------
 
ENABLE:ALL
 
1 row selected.

Recompile procedure:

ALTER PROCEDURE unreachable_code COMPILE;

Result:

SP2-0805: Procedure altered with compilation warnings

Show errors:

SHOW ERRORS

Result:

Errors for PROCEDURE UNREACHABLE_CODE:
 
LINE/COL ERROR
-------- -----------------------------------------------------------------
1/1      PLW-05018: unit UNREACHABLE_CODE omitted optional AUTHID clause;
         default value DEFINER used
 
7/5      PLW-06002: Unreachable code

For more information, see DBMS_WARNING package in Oracle Database PL/SQL Packages and Types Reference and PLW- messages in Oracle Database Error Messages

Overview of Exception Handling

Exceptions can arise from design faults, coding mistakes, hardware failures, and many other sources. You cannot anticipate all possible exceptions, but you can code exception handlers that allow your program to continue to operate in their presence.

An exception can be either internally defined (by the run-time system) or user-defined. Examples of internally defined exceptions are ORA-22056 (value string is divided by zero) and ORA-27102 (out of memory). Some common internal exceptions have predefined names, such as ZERO_DIVIDE and STORAGE_ERROR. The other internal exceptions can be given names.

You can define your own exceptions in the declarative part of any PL/SQL block, subprogram, or package. For example, you might define an exception named insufficient_funds to flag overdrawn bank accounts. User-defined exceptions must be given names.

When an error occurs, an exception is raised. That is, normal execution stops and control transfers to the exception-handling part of your PL/SQL block or subprogram. Internal exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions must be raised explicitly by RAISE statements or invocations of the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

To handle raised exceptions, you write separate exception handlers. After an exception handler runs, the current block stops running and the enclosing block resumes with the next statement. If there is no enclosing block, control returns to the host environment. For information about managing errors when using BULK COLLECT, see "Handling FORALL Exceptions".

Example 11-3 calculates a price-to-earnings ratio for a company. If the company has zero earnings, the division operation raises the predefined exception ZERO_DIVIDE, the execution of the block is interrupted, and control transfers to the exception handlers. The optional OTHERS handler handles all exceptions that the block does not name specifically.

Example 11-3 Anonymous Block with Exception Handlers

DECLARE
  stock_price   NUMBER := 9.73;
  net_earnings  NUMBER := 0;
  pe_ratio      NUMBER;
BEGIN
  pe_ratio := stock_price / net_earnings;  -- causes division-by-zero error
  DBMS_OUTPUT.PUT_LINE('Price/earnings ratio = ' || pe_ratio);
EXCEPTION
  WHEN ZERO_DIVIDE THEN  -- handles division-by-zero error
    DBMS_OUTPUT.PUT_LINE('Company had zero earnings.');
    pe_ratio := NULL;
  WHEN OTHERS THEN  -- handles all other errors
    DBMS_OUTPUT.PUT_LINE('Another kind of error occurred.');
    pe_ratio := NULL;
END;
/

Result:

Company had zero earnings.

Example 11-4 avoids the exception that Example 11-3 handles.

Example 11-4 Avoiding the Exception that Example 11-3 Handles

DECLARE
  stock_price   NUMBER := 9.73;
  net_earnings  NUMBER := 0;
  pe_ratio      NUMBER;
BEGIN
  pe_ratio :=
    CASE net_earnings
      WHEN 0 THEN NULL
      ELSE stock_price / net_earnings
    END;
END;
/

Topics:

Advantages of Exceptions

With exceptions, you can reliably handle potential errors from many statements with a single exception handler, as in Example 11-5.

Example 11-5 Managing Multiple Errors with a Single Exception Handler

DECLARE
  emp_column  VARCHAR2(30) := 'last_name';
  table_name  VARCHAR2(30) := 'emp';
  temp_var    VARCHAR2(30);
BEGIN
  temp_var := emp_column;

  SELECT COLUMN_NAME INTO temp_var
  FROM USER_TAB_COLS 
  WHERE TABLE_NAME = 'EMPLOYEES'
  AND COLUMN_NAME = UPPER(emp_column);

  temp_var := table_name;

  SELECT OBJECT_NAME INTO temp_var
  FROM USER_OBJECTS
  WHERE OBJECT_NAME = UPPER(table_name)
  AND OBJECT_TYPE = 'TABLE';

EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE ('No Data found for SELECT on ' || temp_var);
END;
/

Instead of checking for an error at every point where it might occur, add an exception handler to your PL/SQL block. If the exception is ever raised in that block (including inside a sub-block), it is handled.

Sometimes the error is not immediately obvious, and cannot be detected until later when you perform calculations using bad data. Again, a single exception handler can trap all division-by-zero errors, bad array subscripts, and so on.

If you must check for errors at a specific spot, you can enclose a single statement or a group of statements inside its own BEGIN END block with its own exception handler. You can make the checking as general or as precise as you like.

Isolating exception handlers makes the rest of the program easier to read and understand.

Guidelines for Avoiding and Handling Exceptions

Because reliability is crucial for database programs, use both error checking and exception handling to ensure your program can handle all possibilities:

  • Add exception handlers whenever errors can occur.

    Errors are especially likely during arithmetic calculations, string manipulation, and database operations. Errors can also occur at other times, for example if a hardware failure with disk storage or memory causes a problem that has nothing to do with your code; but your code still must take corrective action.

  • Add error-checking code whenever bad input data can cause an error.

    Expect that at some time, your code will be passed incorrect or null parameters, that your queries will return no rows or more rows than you expect.

    Test your code with different combinations of bad data to see what potential errors arise.

  • Make your programs robust enough to work even if the database is not in the state you expect.

    For example, perhaps a table you query will have columns added or deleted, or their types changed. You can avoid such problems by declaring individual variables with %TYPE qualifiers, and declaring records to hold query results with %ROWTYPE qualifiers.

  • Handle named exceptions whenever possible, instead of using WHEN OTHERS in exception handlers.

    Learn the names and causes of the predefined exceptions. If your database operations might cause particular ORA-n errors, associate names with these errors so you can write handlers for them.

  • Write out debugging information in your exception handlers.

    You might store such information in a separate table. If so, do it by invoking a subprogram declared with the PRAGMA AUTONOMOUS_TRANSACTION, so that you can commit your debugging information, even if you roll back the work that the main subprogram was doing.

  • Carefully consider whether each exception handler should commit the transaction, roll it back, or let it continue.

    No matter how severe the error is, you want to leave the database in a consistent state and avoid storing any bad data.

Predefined Exceptions

An internal exception is raised automatically if your PL/SQL program violates a database rule or exceeds a system-dependent limit. PL/SQL predefines some common ORA-n errors as exceptions. For example, PL/SQL raises the predefined exception NO_DATA_FOUND if a SELECT INTO statement returns no rows.

You can use the pragma EXCEPTION_INIT to associate exception names with other Oracle Database error codes that you can anticipate. To handle unexpected Oracle Database errors, you can use the OTHERS handler. In this handler, you can invoke the functions SQLCODE and SQLERRM to return the Oracle Database error code and message text. Once you know the error code, you can use it with pragma EXCEPTION_INIT and write a handler specifically for that error.

PL/SQL declares predefined exceptions globally in package STANDARD. You need not declare them yourself. You can write handlers for predefined exceptions using the names in Table 11-2.

Table 11-2 Predefined Exceptions

Exception Name ORA Error SQLCODE Raised When ...

ACCESS_INTO_NULL

06530

-6530

A program attempts to assign values to the attributes of an uninitialized object

CASE_NOT_FOUND

06592

-6592

None of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause.

COLLECTION_IS_NULL

06531

-6531

A program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray.

CURSOR_ALREADY_OPEN

06511

-6511

A program attempts to open an open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers, so your program cannot open that cursor inside the loop.

DUP_VAL_ON_INDEX

00001

-1

A program attempts to store duplicate values in a column that is constrained by a unique index.

INVALID_CURSOR

01001

-1001

A program attempts a cursor operation that is not allowed, such as closing an unopened cursor.

INVALID_NUMBER

01722

-1722

n a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clause expression in a bulk FETCH statement does not evaluate to a positive number.

LOGIN_DENIED

01017

-1017

A program attempts to log on to the database with an invalid user name or password.

NO_DATA_FOUND

01403

+100

A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an associative array.

Because this exception is used internally by some SQL functions to signal completion, you must not rely on this exception being propagated if you raise it in a function that is invoked as part of a query.

NOT_LOGGED_ON

01012

-1012

A program issues a database call without being connected to the database.

PROGRAM_ERROR

06501

-6501

PL/SQL has an internal problem.

ROWTYPE_MISMATCH

06504

-6504

The host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. When an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible.

SELF_IS_NULL

30625

-30625

A program attempts to invoke a MEMBER method, but the instance of the ADT was not initialized. The built-in parameter SELF points to the object, and is always the first parameter passed to a MEMBER method.

STORAGE_ERROR

06500

-6500

PL/SQL ran out of memory or memory was corrupted.

SUBSCRIPT_BEYOND_COUNT

06533

-6533

A program references a nested table or varray element using an index number larger than the number of elements in the collection.

SUBSCRIPT_OUTSIDE_LIMIT

06532

-6532

A program references a nested table or varray element using an index number (-1 for example) that is outside the legal range.

SYS_INVALID_ROWID

01410

-1410

The conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid.

TIMEOUT_ON_RESOURCE

00051

-51

A time out occurs while the database is waiting for a resource.

TOO_MANY_ROWS

01422

-1422

A SELECT INTO statement returns multiple rows.

VALUE_ERROR

06502

-6502

An arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL stops the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements, INVALID_NUMBER is raised.)

ZERO_DIVIDE

01476

-1476

A program attempts to divide a number by zero.


User-Defined Exceptions

PL/SQL lets you define exceptions of your own. Unlike a predefined exception, a user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR. The latter lets you associate an error message with the user-defined exception.

Topics:

Exception Declarations

Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or package. You declare an exception by introducing its name, followed by the keyword EXCEPTION. For example:

DECLARE
  past_due  EXCEPTION;
BEGIN
  NULL;
END;
/

Exception and variable declarations are similar. But remember, an exception is an error condition, not a data item. Unlike variables, exceptions cannot appear in assignment statements or SQL statements. However, the same scope rules apply to variables and exceptions.

Exception Scope

You cannot declare an exception twice in the same block. You can, however, declare the same exception in two different blocks.

Exceptions declared in a block are considered local to that block and global to all its sub-blocks. Because a block can reference only local or global exceptions, enclosing blocks cannot reference exceptions declared in a sub-block.

If you redeclare a global exception in a sub-block, the local declaration prevails. The sub-block cannot reference the global exception, unless the exception is declared in a labeled block and you qualify its name with the block label block_label.exception_name.

Example 11-6 shows the scope rules.

Example 11-6 Scope of Exceptions

DECLARE
  past_due  EXCEPTION;
  acct_num  NUMBER;
BEGIN
  DECLARE  -- sub-block begins
    past_due EXCEPTION;  -- this declaration prevails
    acct_num NUMBER;
    due_date DATE := SYSDATE - 1;
    todays_date DATE := SYSDATE;
  BEGIN
    IF due_date < todays_date THEN
      RAISE past_due;  -- this is not handled
    END IF;
  END;  -- sub-block ends
EXCEPTION
  -- Does not handle raised exception
  WHEN past_due THEN
    DBMS_OUTPUT.PUT_LINE ('Handling PAST_DUE exception.');
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE
      ('Could not recognize PAST_DUE_EXCEPTION in this scope.');
END;
/

Result:

Could not recognize PAST_DUE_EXCEPTION in this scope.

The enclosing block does not handle the raised exception because the declaration of past_due in the sub-block prevails. Though they share the same name, the two past_due exceptions are different, just as the two acct_num variables share the same name but are different variables. Thus, the RAISE statement and the WHEN clause refer to different exceptions. To have the enclosing block handle the raised exception, you must remove its declaration from the sub-block or define an OTHERS handler.

Associating Exceptions with Numbers

To handle an error condition (typically an ORA-n message) that has no predefined name, you must use the OTHERS handler or the pragma EXCEPTION_INIT. A pragma is a compiler directive that is processed at compile time, not at run time.

In PL/SQL, the pragma EXCEPTION_INIT tells the compiler to associate an exception name with an Oracle Database error number. That lets you refer to any internal exception by name and to write a specific handler for it. When you see an error stack, or sequence of error messages, the one on top is the one that you can trap and handle.

You code the pragma EXCEPTION_INIT in the declarative part of a PL/SQL block, subprogram, or package using this syntax:

PRAGMA EXCEPTION_INIT(exception_name, -Oracle_error_number);

where exception_name is the name of a previously declared exception and the number is a negative value corresponding to an ORA-n error. The pragma must appear somewhere after the exception declaration in the same declarative section, as shown in Example 11-7.

Example 11-7 PRAGMA EXCEPTION_INIT

DECLARE
  deadlock_detected EXCEPTION;
  PRAGMA EXCEPTION_INIT(deadlock_detected, -60);
BEGIN
  NULL; -- Some operation that causes an ORA-00060 error
EXCEPTION
  WHEN deadlock_detected THEN
    NULL; -- handle the error
END;
/

User-Defined Error Messages

The RAISE_APPLICATION_ERROR procedure lets you issue user-defined ORA-n error messages from stored subprograms. That way, you can report errors to your application and avoid returning unhandled exceptions.

To invoke RAISE_APPLICATION_ERROR, use this syntax:

RAISE_APPLICATION_ERROR (error_number, message[, {TRUE | FALSE}]);

where error_number is a negative integer in the range -20000..-20999 and message is a character string of at most 2048 bytes. If the optional third parameter is TRUE, the error is placed on the stack of previous errors. If the parameter is FALSE (the default), the error replaces all previous errors.

Note:

RAISE_APPLICATION_ERROR is part of package DBMS_STANDARD; therefore, you need not qualify references to it.

An application can invoke RAISE_APPLICATION_ERROR only from an running stored subprogram or method. When invoked, RAISE_APPLICATION_ERROR ends the subprogram and returns a user-defined error number and message to the application. The error number and message can be trapped like any Oracle Database error.

Example 11-8 invokes RAISE_APPLICATION_ERROR if the current schema owns fewer than 1000 tables.

Example 11-8 RAISE_APPLICATION_ERROR Procedure

DECLARE
  num_tables NUMBER;
BEGIN
  SELECT COUNT(*) INTO num_tables FROM USER_TABLES;
  IF num_tables < 1000 THEN
    /* Issue your own error code (ORA-20101)
       with your own error message. You need not
       qualify RAISE_APPLICATION_ERROR with
       DBMS_STANDARD */
    RAISE_APPLICATION_ERROR
      (-20101, 'Expecting at least 1000 tables');
  ELSE
    -- Do rest of processing (for nonerror case)
    NULL;
  END IF;
END;
/

Result:

DECLARE
*
ERROR at line 1:
ORA-20101: Expecting at least 1000 tables
ORA-06512: at line 10

The invoking application gets a PL/SQL exception, which it can process using the error-reporting functions SQLCODE and SQLERRM in an OTHERS handler. Also, it can use the pragma EXCEPTION_INIT to map specific error numbers returned by RAISE_APPLICATION_ERROR to exceptions of its own, as this Pro*C example shows:

EXEC SQL EXECUTE
  /* Execute embedded PL/SQL block using host
     variables v_emp_id and v_amount, which were
     assigned values in the host environment. */
DECLARE
  null_salary EXCEPTION;
  /* Map error number returned by RAISE_APPLICATION_ERROR
     to user-defined exception. */
  PRAGMA EXCEPTION_INIT(null_salary, -20101);
  BEGIN
    raise_salary(:v_emp_id, :v_amount);
  EXCEPTION
    WHEN null_salary THEN
      INSERT INTO emp_audit (employee_id, ...) VALUES (:v_emp_id, ...);
  END;
END-EXEC;

This technique allows the invoking application to handle error conditions in specific exception handlers.

Redeclaring Predefined Exceptions

PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER internally, a handler written for INVALID_NUMBER cannot catch the internal exception. In such cases, you must use dot notation to specify the predefined exception. For example:

BEGIN
  NULL;
EXCEPTION
  WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN
    NULL;  -- handle the error
END;
/

How Exceptions Are Raised

Internal exceptions are raised implicitly by the run-time system, as are user-defined exceptions that you have associated with an Oracle Database error number using EXCEPTION_INIT. Other user-defined exceptions must be raised explicitly, with either RAISE statements or invocations of the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

Raise an exception in a PL/SQL block or subprogram only when an error makes it undesirable or impossible to finish processing. You can explicitly raise a given exception anywhere in the scope of that exception. In Example 11-9, you alert your PL/SQL block to a user-defined exception named out_of_stock.

Example 11-9 Raising a User-Defined Exception

DECLARE
  out_of_stock   EXCEPTION;
  number_on_hand  NUMBER := 0;
BEGIN
  IF number_on_hand < 1 THEN
    RAISE out_of_stock;
  END IF;
EXCEPTION
  WHEN out_of_stock THEN
    DBMS_OUTPUT.PUT_LINE('Out-of-stock error.');
END;
/

Result:

Out-of-stock error.

You can also raise a predefined exception explicitly. That way, an exception handler written for the predefined exception can process other errors, as Example 11-10 shows.

Example 11-10 Raising a Predefined Exception

DECLARE
  acct_type INTEGER := 7;
BEGIN
  IF acct_type NOT IN (1, 2, 3) THEN
    RAISE INVALID_NUMBER;  -- raise predefined exception
  END IF;
EXCEPTION
  WHEN INVALID_NUMBER THEN
     DBMS_OUTPUT.PUT_LINE
       ('HANDLING INVALID INPUT BY ROLLING BACK.');
     ROLLBACK;
END;
/

Result:

HANDLING INVALID INPUT BY ROLLING BACK.

How Exceptions Propagate

When an exception is raised, if PL/SQL cannot find a handler for it in the current block or subprogram, the exception propagates. That is, the exception reproduces itself in successive enclosing blocks until a handler is found or there are no more blocks to search. If no handler is found, PL/SQL returns an unhandled exception error to the host environment.

Exceptions cannot propagate across remote subprogram calls done through database links. A PL/SQL block cannot catch an exception raised by a remote subprogram. For a workaround, see "User-Defined Error Messages".

Figure 11-1, Figure 11-2, and Figure 11-3 illustrate the basic propagation rules.

Figure 11-1 Propagation Rules: Example 1

Propagation Rules: Example 1
Description of "Figure 11-1 Propagation Rules: Example 1"

Figure 11-2 Propagation Rules: Example 2

Propagation Rules: Example 2
Description of "Figure 11-2 Propagation Rules: Example 2"

Figure 11-3 Propagation Rules: Example 3

Propagation Rules: Example 3
Description of "Figure 11-3 Propagation Rules: Example 3"

An exception can propagate beyond its scope, that is, beyond the block in which it was declared, as shown in Example 11-11.

Example 11-11 Scope of an Exception

BEGIN
  DECLARE  -- sub-block begins
    past_due     EXCEPTION;
    due_date     DATE := trunc(SYSDATE) - 1;
    todays_date  DATE := trunc(SYSDATE);
  BEGIN
    IF due_date < todays_date THEN
      RAISE past_due;
    END IF;
  END;  -- sub-block ends
EXCEPTION
  WHEN OTHERS THEN
    ROLLBACK;
END;
/

Because the block that declares the exception past_due has no handler for it, the exception propagates to the enclosing block. But the enclosing block cannot reference the name PAST_DUE, because the scope where it was declared no longer exists. Once the exception name is lost, only an OTHERS handler can catch the exception. If there is no handler for a user-defined exception, the invoking application gets ORA-06510.

Reraising an Exception

Sometimes, you want to reraise an exception, that is, handle it locally, then pass it to an enclosing block. For example, you might want to roll back a transaction in the current block, then log the error in an enclosing block.

To reraise an exception, use a RAISE statement without an exception name, which is allowed only in an exception handler, as in Example 11-12.

Example 11-12 Reraising an Exception

DECLARE
  salary_too_high   EXCEPTION;
  current_salary    NUMBER := 20000;
  max_salary        NUMBER := 10000;
  erroneous_salary  NUMBER;
BEGIN
  BEGIN  -- sub-block begins
    IF current_salary > max_salary THEN
      RAISE salary_too_high;  -- raise the exception
    END IF;
  EXCEPTION
    WHEN salary_too_high THEN
      -- first step in handling the error
      DBMS_OUTPUT.PUT_LINE('Salary ' || erroneous_salary ||' is out of range.');
      DBMS_OUTPUT.PUT_LINE ('Maximum salary is ' || max_salary || '.');
      RAISE;  -- reraise exception
  END;  -- sub-block ends
EXCEPTION
  WHEN salary_too_high THEN
    -- handle error more thoroughly
    erroneous_salary := current_salary;
    current_salary := max_salary;

    DBMS_OUTPUT.PUT_LINE (
      'Revising salary from ' || erroneous_salary ||
      ' to ' || current_salary || '.'
    );
END;
/

Result:

Salary  is out of range.
Maximum salary is 10000.
Revising salary from 20000 to 10000.

Exception Handlers

When an exception is raised, normal execution of your PL/SQL block or subprogram stops and control transfers to its exception-handling part, which is formatted as follows:

EXCEPTION
  WHEN exception1 THEN -- handler for exception1
    sequence_of_statements1
  WHEN exception2 THEN -- another handler for exception2
    sequence_of_statements2
  ...
  WHEN OTHERS THEN -- optional handler for all other errors
    sequence_of_statements3
END;

To catch raised exceptions, you write exception handlers. Each handler consists of a WHEN clause, which specifies an exception, followed by a sequence of statements to run when that exception is raised. These statements complete execution of the block or subprogram; control does not return to where the exception was raised. In other words, you cannot resume processing where you left off.

The optional OTHERS exception handler, which is always the last handler in a block or subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or subprogram can have only one OTHERS handler. Use of the OTHERS handler guarantees that no exception is unhandled.

If you want two or more exceptions to run the same sequence of statements, list the exception names in the WHEN clause, separating them by the keyword OR, as follows:

EXCEPTION
  WHEN over_limit OR under_limit OR VALUE_ERROR THEN
    -- handle the error

If any of the exceptions in the list is raised, the associated sequence of statements runs. The keyword OTHERS cannot appear in the list of exception names; it must appear by itself. You can have any number of exception handlers, and each handler can associate a list of exceptions with a sequence of statements. However, an exception name can appear only once in the exception-handling part of a PL/SQL block or subprogram.

The usual scoping rules for PL/SQL variables apply, so you can reference local and global variables in an exception handler. However, when an exception is raised inside a cursor FOR loop, the cursor is closed implicitly before the handler is invoked. Therefore, the values of explicit cursor attributes are not available in the handler.

Topics:

Exceptions Raised in Declarations

In declarations, faulty initialization expressions can raise exceptions, but exception handlers cannot handle them, as Example 11-13 shows.

Example 11-13 Raising an Exception in a Declaration

DECLARE
  credit_limit CONSTANT NUMBER(3) := 5000;  -- Maximum value is 999
BEGIN
  NULL;
EXCEPTION
  WHEN OTHERS THEN
    -- Cannot catch exception. This handler is never invoked.
    DBMS_OUTPUT.PUT_LINE
      ('Can''t handle an exception in a declaration.');
END;
/

Result:

DECLARE
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: number precision too large
ORA-06512: at line 2

Handlers in the current block cannot catch the raised exception because an exception raised in a declaration propagates immediately to the enclosing block.

Exceptions Raised in Exception Handlers

When an exception occurs in an exception handler, that same handler cannot catch the exception. An exception raised inside a handler propagates immediately to the enclosing block, which is searched to find a handler for this exception. From there on, the exception propagates normally. For example:

EXCEPTION
  WHEN INVALID_NUMBER THEN
    INSERT INTO ... -- might raise DUP_VAL_ON_INDEX
  WHEN DUP_VAL_ON_INDEX THEN -- cannot catch exception
END;

Transferring Control to or from Exception Handlers

A GOTO statement can transfer control from an exception handler into an enclosing block.

A GOTO statement cannot transfer control into an exception handler, or from an exception handler into the current block.

Error Code and Error Message Retrieval

In an exception handler, you can retrieve the error code with the built-in function SQLCODE. To retrieve the associated error message, you can use either the packaged function DBMS_UTILTY.FORMAT_ERROR_STACK or the built-in function SQLERRM.

SQLERRM returns a maximum of 512 bytes, which is the maximum length of an Oracle Database error message (including the error code, nested messages, and message inserts, such as table and column names). DBMS_UTILTY.FORMAT_ERROR_STACK returns the full error stack, up to 2000 bytes. Therefore, DBMS_UTILTY.FORMAT_ERROR_STACK is recommended over SQLERRM, except when using the FORALL statement with its SAVE EXCEPTIONS clause. With SAVE EXCEPTIONS, use SQLERRM, as in Example 12-11.

See Also:

A SQL statement cannot invoke SQLCODE or SQLERRM. To use their values in a SQL statement, assign them to local variables first, as in Example 11-14.

Example 11-14 Displaying SQLCODE and SQLERRM

DROP TABLE errors;
CREATE TABLE errors (
  code      NUMBER,
  message   VARCHAR2(64),
  happened  TIMESTAMP
);

DECLARE
  name    EMPLOYEES.LAST_NAME%TYPE;
  v_code  NUMBER;
  v_errm  VARCHAR2(64);
BEGIN
  SELECT last_name INTO name
  FROM EMPLOYEES
  WHERE EMPLOYEE_ID = -1;
EXCEPTION
  WHEN OTHERS THEN
    v_code := SQLCODE;
    v_errm := SUBSTR(SQLERRM, 1, 64);
    DBMS_OUTPUT.PUT_LINE
      ('Error code ' || v_code || ': ' || v_errm);
 
    /* Invoke another procedure,
       declared with PRAGMA AUTONOMOUS_TRANSACTION,
       to insert information about errors. */
 
    INSERT INTO errors (code, message, happened)
    VALUES (v_code, v_errm, SYSTIMESTAMP);
END;
/

Result:

Error code 100: ORA-01403: no data found

Continuing Execution After an Exception Is Raised

An exception handler lets you recover from an otherwise irrecoverable error before exiting a block. When the handler completes, the block terminates—you cannot return to the block from the exception handler.

In Example 11-15, if the SELECT INTO statement raises ZERO_DIVIDE, execution cannot resume with the INSERT statement.

Example 11-15 Exception Handler

DROP TABLE employees_temp;
CREATE TABLE employees_temp AS
  SELECT employee_id, salary, commission_pct
  FROM employees;

DECLARE
  sal_calc NUMBER(8,2);
BEGIN
  INSERT INTO employees_temp (employee_id, salary, commission_pct)
  VALUES (301, 2500, 0);

  SELECT (salary / commission_pct) INTO sal_calc
  FROM employees_temp
  WHERE employee_id = 301;

  INSERT INTO employees_temp VALUES (302, sal_calc/100, .1);
EXCEPTION
  WHEN ZERO_DIVIDE THEN
    NULL;
END;
/

You can still handle an exception for a statement, then continue with the next statement. Place the statement in its own sub-block with its own exception handlers. If an error occurs in the sub-block, a local handler can catch the exception. When the sub-block ends, the enclosing block continues to run at the point where the sub-block ends, as shown in Example 11-16.

Example 11-16 Continuing After an Exception

DECLARE
  sal_calc NUMBER(8,2);
BEGIN
  INSERT INTO employees_temp (employee_id, salary, commission_pct)
  VALUES (303, 2500, 0);
 
  BEGIN  -- sub-block begins
    SELECT (salary / commission_pct) INTO sal_calc
    FROM employees_temp
    WHERE employee_id = 301;
  EXCEPTION
    WHEN ZERO_DIVIDE THEN
      sal_calc := 2500;
  END; -- sub-block ends
 
  INSERT INTO employees_temp (employee_id, salary, commission_pct)
  VALUES (304, sal_calc/100, .1);
EXCEPTION
  WHEN ZERO_DIVIDE THEN
    NULL;
END;
/

In Example 11-16, if the SELECT INTO statement raises a ZERO_DIVIDE exception, the local handler catches it and sets sal_calc to 2500. Execution of the handler is complete, so the sub-block terminates, and execution continues with the INSERT statement.

You can also perform a sequence of DML operations where some might fail, and process the exceptions only after the entire operation is complete, as described in "Handling FORALL Exceptions".

Retrying a Transaction

After an exception is raised, rather than abandon your transaction, you might want to retry it. The technique is:

  1. Encase the transaction in a sub-block.

  2. Place the sub-block inside a loop that repeats the transaction.

  3. Before starting the transaction, mark a savepoint. If the transaction succeeds, commit, then exit from the loop. If the transaction fails, control transfers to the exception handler, where you roll back to the savepoint undoing any changes, then try to fix the problem.

In Example 11-17, the INSERT statement might raise an exception because of a duplicate value in a unique column. In that case, change the value that must be unique and continue with the next loop iteration. If the INSERT succeeds, exit from the loop immediately. With this technique, use a FOR or WHILE loop to limit the number of attempts.

Example 11-17 Retrying a Transaction After an Exception

DROP TABLE results;
CREATE TABLE results (
  res_name VARCHAR(20),
  res_answer VARCHAR2(3)
);
 
CREATE UNIQUE INDEX res_name_ix ON results (res_name);
 
INSERT INTO results (res_name, res_answer)
VALUES ('SMYTHE', 'YES');
 
INSERT INTO results (res_name, res_answer) 
VALUES ('JONES', 'NO');
 
DECLARE
  name    VARCHAR2(20) := 'SMYTHE';
  answer  VARCHAR2(3) := 'NO';
  suffix  NUMBER := 1;
BEGIN
  FOR i IN 1..5 LOOP  -- try 5 times
    BEGIN  -- sub-block begins
       SAVEPOINT start_transaction;
 
       -- Remove rows from a table of survey results:
       DELETE FROM results WHERE res_answer = 'NO';
 
       -- Add a survey respondent's name and answers:
       INSERT INTO results  (res_name, res_answer)
       VALUES (name, answer);
       -- If two respondents have same name, raise DUP_VAL_ON_INDEX.
 
       COMMIT;
       EXIT;
    EXCEPTION
      WHEN DUP_VAL_ON_INDEX THEN
        ROLLBACK TO start_transaction;  -- undo changes
        suffix := suffix + 1;           -- try to fix problem
        name := name || TO_CHAR(suffix);
    END;  -- sub-block ends
  END LOOP;
END;
/

Identifying Exception Locations With Locator Variables

Using one exception handler for a sequence of statements, such as INSERT, DELETE, or UPDATE statements, can mask the statement that caused an error. If you must know which statement failed, you can use a locator variable, as in Example 11-18.

Example 11-18 Identifying Exception Locations with Locator Variables

CREATE OR REPLACE PROCEDURE loc_var AS
  stmt_no  NUMBER;
  name_    VARCHAR2(100);
BEGIN
  stmt_no := 1;  -- designates 1st SELECT statement

  SELECT table_name INTO name_
  FROM user_tables
  WHERE table_name LIKE 'ABC%';

  stmt_no := 2;  -- designates 2nd SELECT statement

  SELECT table_name INTO name_
  FROM user_tables
  WHERE table_name LIKE 'XYZ%';
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE ('Table name not found in query ' || stmt_no);
END;
/
CALL loc_var();

Result:

Table name not found in query 1
 
Call completed.

Unhandled Exceptions

If it cannot find a handler for a raised exception, PL/SQL returns an unhandled exception error to the host environment, which determines the outcome. For example, in the Oracle Precompilers environment, any database changes made by a failed SQL statement or PL/SQL block are rolled back.

Unhandled exceptions can also affect subprograms. If you exit a subprogram successfully, PL/SQL assigns values to OUT parameters. However, if you exit with an unhandled exception, PL/SQL does not assign values to OUT parameters (unless they are NOCOPY parameters). Also, if a stored subprogram fails with an unhandled exception, PL/SQL does not roll back database work done by the subprogram.

You can avoid unhandled exceptions by coding an OTHERS handler at the topmost level of every PL/SQL program.