PLLes 08
PLLes 08
PLLes 08
Lesson Aim
You have learned to write PL/SQL blocks with a declarative section and an
executable section. All the SQL and PL/SQL code that must be executed is
written in the executable block.
So far we have assumed that the code works satisfactorily if we take care of
compile-time errors. However, the code may cause some unanticipated errors
at run time. In this lesson, you learn how to deal with such errors in the
PL/SQL block.
SET SERVEROUTPUT ON
DECLARE
lname VARCHAR2(15);
BEGIN
SELECT last_name INTO lname FROM employees WHERE
first_name='John';
DBMS_OUTPUT.PUT_LINE ('John''s last name is : '
||lname);
END;
/
Example of an Exception
Consider the example shown in the slide. There are no syntax errors in the
code, which means you must be able to successfully execute the anonymous
block. The select statement in the block retrieves the last_name of John. You
see the following output when you execute the code:
The code does not work as expected. You expected the SELECT statement to
retrieve only one row; however, it retrieves multiple rows. Such errors that
occur at run time are called exceptions. When an exception occurs, the
PL/SQL block is terminated. You can handle such exceptions in your PL/SQL
block.
SET SERVEROUTPUT ON
DECLARE
lname VARCHAR2(15);
BEGIN
SELECT last_name INTO lname FROM employees WHERE
first_name='John';
DBMS_OUTPUT.PUT_LINE ('John''s last name is : '
||lname);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE (' Your select statement
retrieved multiple rows. Consider using a
cursor.');
END;
/
8-4 Copyright © 2006, Oracle. All rights reserved.
Unlike earlier, the PL/SQL program does not terminate abruptly. When the
exception is raised, the control shifts to the exception section and all the
statements in the exception section are executed. The PL/SQL block
terminates with normal, successful completion.
Is the
exception Terminate
trapped? No abruptly.
Yes
Terminate
gracefully.
Handling Exceptions
Trapping an Exception
Include an EXCEPTION section in your PL/SQL program to trap exceptions. If
the exception is raised in the executable section of the block, processing then
branches to the corresponding exception handler in the exception section of
the block. If PL/SQL successfully handles the exception, the exception does
not propagate to the enclosing block or to the calling environment. The
PL/SQL block terminates successfully.
Propagating an Exception
If the exception is raised in the executable section of the block and there is no
corresponding exception handler, the PL/SQL block terminates with failure
and the exception is propagated to an enclosing block or to the calling
environment. The calling environment can be any application (such as
SQL*Plus that invokes the PL/SQL program).
Exception Types
There are three types of exceptions.
Syntax:
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
Trapping Exceptions
You can trap any error by including a corresponding handler within the
exception handling section of the PL/SQL block. Each handler consists of a
WHEN clause, which specifies an exception name, followed by a sequence of
statements to be executed when that exception is raised. You can include any
number of handlers within an EXCEPTION section to handle specific
exceptions. However, you cannot have multiple handlers for a single
exception.
exception Is the standard name of a predefined exception or the name of a user-
In the syntax: defined exception declared within the declarative section
statement Is one or more PL/SQL or SQL statements
OTHERS Is an optional exception-handling clause that traps any exceptions
that have not been explicitly handled
Non-Predefined Error
1. Declare the name of the exception in the declarative section.
Syntax:
exception EXCEPTION;
In the syntax, exception is the name of the exception.
2. Associate the declared exception with the standard Oracle server error
number using the PRAGMA EXCEPTION_INIT function.
Syntax:
PRAGMA EXCEPTION_INIT(exception, error_number);
In the syntax, exception is the previously declared exception and
error_number is a standard Oracle server error number.
3. Reference the declared exception within the corresponding exception-
handling routine.
Example
The example in the slide tries to insert the value NULL for the
department_name column of the departments table. However, the operation
is not successfulOracle
because department_name
Database is a NOT NULL
10g: PL/SQL Fundamentals column. Note the
8-15
following line in the example:
Functions for Trapping Exceptions
Example
DECLARE
error_code NUMBER;
error_message VARCHAR2(255);
BEGIN
...
EXCEPTION
...
WHEN OTHERS THEN
ROLLBACK;
error_code := SQLCODE ;
error_message := SQLERRM ;
INSERT INTO errors (e_user, e_date, error_code,
error_message) VALUES(USER,SYSDATE,error_code,
error_message);
END;
/
Calling Environments
Instead of trapping an exception within the PL/SQL block, propagate the
exception to allow the calling environment to handle it. Each calling
environment has its own way of displaying and accessing errors.
DECLARE
. . .
no_rows exception;
integrity exception;
PRAGMA EXCEPTION_INIT (integrity, -2292);
BEGIN
FOR c_record IN emp_cursor LOOP
Subblocks can handle BEGIN
SELECT ...
an exception or pass UPDATE ...
the exception to the IF SQL%NOTFOUND THEN
enclosing block. RAISE no_rows;
END IF;
END;
END LOOP;
EXCEPTION
WHEN integrity THEN ...
WHEN no_rows THEN ...
END;
/
Syntax:
raise_application_error (error_number,
message[, {TRUE | FALSE}]);
RAISE_APPLICATION_ERROR Procedure
Use the RAISE_APPLICATION_ERROR procedure to communicate a predefined
exception interactively by returning a nonstandard error code and error
message. With RAISE_APPLICATION_ERROR, you can report errors to your
application and avoid returning unhandled exceptions.
In the syntax:
error_number Is a user-specified number for the exception between –20000
and –20999
message Is the user-specified message for the exception; is a character string
up to 2,048 bytes long
TRUE | FALSE Is an optional Boolean parameter (If TRUE, the error is placed
on the stack of previous errors. If FALSE, which is the default, the
error replaces all previous errors.)
Executable section:
BEGIN
...
DELETE FROM employees
WHERE manager_id = v_mgr;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20202,
'This is not a valid manager');
END IF;
...
Exception section:
...
EXCEPTION
WHEN NO_DATA_FOUND THEN
RAISE_APPLICATION_ERROR (-20201,
'Manager is not a valid employee.');
END;
/
Summary
In this lesson, you learned how to deal with different types of exceptions. In
PL/SQL, a warning or error condition at run time is called an exception.
Predefined exceptions are error conditions that are defined by the Oracle
server. Non-predefined exceptions can be any standard Oracle server errors.
User-defined exceptions are exceptions specific to your application. The
PRAGMA EXCEPTION_INIT function can be used to associate a declared
exception name with an Oracle server error.
You can define exceptions of your own in the declarative section of any
PL/SQL block.
For example, you can define an exception named INSUFFICIENT_FUNDS to
flag overdrawn bank accounts.
When an error occurs, an exception is raised. Normal execution stops and
transfers control to the exception-handling section of your PL/SQL block.
Internal exceptions are raised implicitly (automatically) by the run-time
system; however, user-defined exceptions must be raised explicitly. To
handle raised exceptions, you write separate routines called exception
handlers.
Practice 8: Overview
In this practice, you create exception handlers for specific situations.