0% found this document useful (0 votes)
192 views12 pages

Error Handling: Any Well-Written Program Must Have The Capability To Handle Errors

Download as doc, pdf, or txt
Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1/ 12

Error Handling

Any well-written program must have the capability to handle errors


intelligently and recover from them if possible. PL/SQL implements
error handling with exceptions and exception handlers. Exceptions
can be associated with Oracle errors or with your own user-defined
errors.

What Is an Exception?
By using exceptions and exception handlers, you can make your PL/SQL programs
robust and able to deal with both unexpected and expected errors during execution.

What kinds of errors can occur in a PL/SQL program?

DECLARE
v_NumAuthors NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_NumAuthors
FROM aauthor;
END;

FROM aauthor;
*
ERROR at line 6:
ORA-06550: line 6, column 6:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 4, column 1:
PL/SQL: SQL Statement ignored
Declaring Exceptions

Exceptions are declared in the declarative section of the block, raised in the
executable section, and handled in the exception section.
We will see how each of these is done in the following sections.

Exception Types
There are three types of exceptions:

Trapping Exceptions

Syntax:
EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]

The exception handling section of the PL/SQL block. Each handler consists of a
WHEN clause, which specifies an exception, followed by a sequence of statements
to be executed when that exception is raised.
In the syntax:

Exception- is the standard name of a predefined exception or the name of a


user 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 unspecified


exceptions.

Guidelines

• Begin the exception-handling section of the block with the EXCEPTION keyword.
• Define several exception handlers, each with its own set of actions, for the block.
• When an exception occurs, PL/SQL processes only one handler before leaving the block.
• Place the OTHERS clause after all other exception-handling clauses.
• You can have only one OTHERS clause.
• Exceptions cannot appear in assignment statements or SQL statements.

Trapping Predefined Oracle Server Errors

Trap a predefined Oracle Server error by referencing its standard name within the
corresponding exception-handling routine.

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
shown on the slide.
Predefined Exceptions syntax:

BEGIN
...

EXCEPTION
WHEN NO_DATA_FOUND THEN
statement1;
statement2;

WHEN TOO_MANY_ROWS THEN


statement1;

WHEN OTHERS THEN


statement1;
statement2;
statement3;
END;

To catch raised exceptions, write exception handlers. Each handler consists of a


WHEN clause, which specifies an exception, followed by a sequence of statements
to be executed when that exception is raised.
These statements complete execution of the block or subprogram; control does not
return to where the exception was raised. Other words, it cannot resume processing
where left off.

The optional OTHERS exception handler, which, if present, is always the last
handler in a block or subprogram, acts as the handler for all exceptions that are not
named specifically. Thus, a block or subprogram can have only one OTHERS
handler.

Note: PL/SQL declares predefined exceptions in the STANDARD package.

It is a good idea to always handle the NO_DATA_FOUND and TOO_MANY_ROWS


exceptions, which are the most common.

Predefined Exceptions in Oracle Server:


FOR EXAMPLE
SET SERVEROUTPUT ON
DECLARE
v_num1 integer := &sv_num1;
v_num2 integer := &sv_num2;
v_result number;
BEGIN
v_result := v_num1 / v_num2;
DBMS_OUTPUT.PUT_LINE ('v_result: '||v_result);
EXCEPTION
WHEN ZERO_DIVIDE THEN
DBMS_OUTPUT.PUT_LINE('A number cannot be divided by zero.');
END;
Enter value for sv_num1: 9
old 2: v_num1 integer := &sv_num1;
new 2: v_num1 integer := 9;
Enter value for sv_num2: 0
old 3: v_num2 integer := &sv_num2;
new 3: v_num2 integer := 0;

A number cannot be divided by zero.

PL/SQL procedure successfully completed.


DECLARE
v_order# NUMBER := &sv_orderno;
v_ordered VARCHAR2(3) := 'NO';
BEGIN
DBMS_OUTPUT.PUT_LINE('Check if the order has items');
SELECT 'YES' INTO v_ordered FROM orderitems WHERE order# = v_order#;
DBMS_OUTPUT.PUT_LINE ('The order has one item');
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE ('The order is not found');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('The order has too many items');
END;

Result :

Enter value for sv_orderno: 1007


Check if the order has items
The order has too many items

PL/SQL procedure successfully completed.

DECLARE
v_customer_no NUMBER := &sv_cusomter_no;
v_customer_name VARCHAR2(50);
BEGIN
SELECT firstname||' '| | lastname INTO v_customer_name FROM customers
WHERE customer# = v_customer_no;
DBMS_OUTPUT.PUT_LINE ('customer name is '||v_customer_name);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('An error has occurred');
END;

Result:

Enter value for sv_cusomter_no: 1019


customer name is JENNIFER SMITH

PL/SQL procedure successfully completed.

Enter value for sv_cusomter_no: 1000


An error has occurred

PL/SQL procedure successfully complete


Trapping Non predefined Oracle Server Errors

To trap a non predefined Oracle server error by declaring it first, or by using the
OTHERS handler. The declared exception is raised implicitly.

In PL/SQL, the PRAGMA EXCEPTION_INIT tells the compiler to associate an


exception name with an Oracle error number. That allows to refer any internal
exception by name and to write a specific handler for it.

Note: PRAGMA (also called pseudoinstructions) is the keyword that signifies that
the statement is a compiler directive, which is not processed when the PL/SQL block
is executed. Rather, it directs the PL/SQL compiler to interpret all occurrences of the
exception name within the block as the associated Oracle server error number.

Example

DEFINE p_deptno = 10
DECLARE
e_emps_remaining EXCEPTION;
PRAGMA EXCEPTION_INIT (e_emps_remaining, -2292);
BEGIN
DELETE FROM dept WHERE deptno = &p_deptno;
COMMIT;
EXCEPTION
WHEN e_emps_remaining THEN
DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' ||TO_CHAR(&p_deptno) || '.
Employees exist. ');
END;
Result:-

Cannot remove dept 10. Employees exist.

PL/SQL procedure successfully completed.

1. Declare the name for the exception within the declarative section.

Syntax
exception EXCEPTION;
where: exception is the name of the exception.

2. Associate the declared exception with the standard Oracle server error number
using the PRAGMA EXCEPTION_INIT statement.
Syntax
PRAGMA EXCEPTION_INIT(exception, error_number);

where: exception is the previously declared exception. error_number is a standard


Oracle Server error number.

3. Reference the declared exception within the corresponding exception-handling


routine.

If there are employees in a department, print a message to the user that the
department cannot be removed.

From the previous example

Trap for Oracle server error number –2292, an integrity constraint violation. That is
replaced with user defined new message for oracle error number(-2292) . The
message cannot remove dept 10. Employees exist.

Error-Trapping Functions

When an exception occurs, you can identify the associated error code or error
message by using two functions. Based on the values of the code or message, you
can decide which subsequent action to take based on the error.

SQLCODE returns the number of the Oracle error for internal exceptions. You can
pass an error number to SQLERRM, which then returns the message associated
with the error number.
Example SQLCODE Values

Example for trapping Error Code and Error Message

DECLARE
v_customer_no NUMBER := &sv_cusomter_no;
v_customer_name VARCHAR2(50);
v_error_code number;
v_error_message varchar2(255);
BEGIN
SELECT firstname||' '| | lastname INTO v_customer_name FROM customers
WHERE customer# = v_customer_no;
DBMS_OUTPUT.PUT_LINE ('customer name is '||v_customer_name);
EXCEPTION
WHEN OTHERS THEN
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
DBMS_OUTPUT.PUT_LINE ('An error has occurred'|| ‘error code is ‘|| v_error_code
|| ‘ error message is ‘|| v_error_message);
END;

Result : -

Enter value for sv_cusomter_no: 1000


An error has occurrederror code is 100 error message is ORA-01403: no data found

PL/SQL procedure successfully completed.


Trapping User-Defined Exceptions

A user-defined exception is an error that is defined by the programmer. The error


that it signifies is not necessarily an Oracle error; it could be an error with the data.

Predefined exceptions, on the other hand, correspond to common SQL and PL/SQL
errors.

You trap a user-defined exception by declaring it and raising it explicitly.

1. Declare the name for the user-defined exception within the declarative section.

Syntax:
exception EXCEPTION;

where: exception is the name of the exception.

2. Use the RAISE statement to raise the exception explicitly within the executable section.

Syntax:

RAISE exception;

where: exception is the previously declared exception.

3. Reference the declared exception within the corresponding exception-handling routine.

Example for User defined exception:

DECLARE
-- Exception to indicate an error condition
high_retail EXCEPTION;
v_error_code number;
v_error_message varchar2(255);
v_retail books.retail%type;
BEGIN
SELECT retail into v_retail from books
WHERE title = 'SHORTEST POEMS';
/* Ensure that there are no duplicates */
IF v_retail > 20 THEN
RAISE high_retail;
END IF;
EXCEPTION
WHEN high_retail THEN
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
DBMS_OUTPUT.PUT_LINE ('An error has occurred'|| 'error code is '|| v_error_code
|| ' error message is '|| v_error_message);
INSERT INTO log_table (loginfo)
VALUES ('shortest poems retail greater than $20');
END;

Result :
An error has occurred error code is 1 error message is User-Defined Exception

PL/SQL procedure successfully completed.

The RAISE_APPLICATION_ERROR Procedure


Syntax:
raise_application_error (error_number,message[,{TRUE| FALSE}]);

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, It can report errors to 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. It 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, the default, the error replaces all previous errors.)

RAISE_APPLICATION_ERROR can be used in either (or both) the executable


section and the exception section of a PL/SQL program. The returned error is
consistent with how the Oracle server produces a predefined, non predefined, or
user-defined error. The error number and message isdisplayed to the user.
DEFINE p_department_desc = 'Information Technology '
DEFINE P_department_number = 300
DECLARE
e_invalid_department EXCEPTION;
BEGIN
UPDATE dept
SET dname = '&p_department_desc'
WHERE deptno = &p_department_number;
IF SQL%NOTFOUND THEN
RAISE e_invalid_department;
END IF;
COMMIT;
EXCEPTION
WHEN e_invalid_department THEN
DBMS_OUTPUT.PUT_LINE('No such department id.');
END;

You might also like