Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 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 racle errors or with your own user-defined
errors.
What Is an Exception?
!y using exceptions and exception handlers" you can ma#e your PL/SQL programs
robust and able to deal with both unexpected and expected errors during execution.
$hat #inds of errors can occur in a PL/SQL program%
&E'L()E
v*+um(uthors +,-!E).
!E/0+
SELE'1 ',+1234
0+1 v*+um(uthors
5)- aauthor.
E+&.
5)- aauthor.
3
E))) at line 67
)(-869987 line 6" column 67
PL/SQL7 )(-88:;<7 table or view does not exist
)(-869987 line ;" column =7
PL/SQL7 SQL Statement ignored
Declaring Exceptions
Exceptions are declared in the declarative section of the bloc#" raised in the
executable section" and handled in the exception section.
$e will see how each of these is done in the following sections.
Exception Types
1here are three types of exceptions7
Trapping Exceptions
Syntax7

EXCEPTION
WHEN exception1 [OR exception2 . . .] THEN
statement1;
statement2;
. . .
[WHEN exception3 [OR exception4 . . .] THEN
statement1;
statement2;
. . .]
[WHEN OTHERS THEN
statement1;
statement2;
. . .]
1he exception handling section of the PL/SQL bloc#. Each handler consists of a
$>E+ clause" which specifies an exception" followed by a se?uence of statements
to be executed when that exception is raised.
0n the syntax7
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.
1>E)S- 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, P!"# processes only one handler before leaving the block.
Place the OTHERS clause after all other exception-handling clauses.
$ou can have only one OTHERS clause.
%xceptions cannot appear in assign&ent state&ents or "# state&ents.
Trapping Predefined Oracle Serer Errors
1rap a predefined racle Server error by referencing its standard name within the
corresponding exception-handling routine.
$hen an exception is raised" normal execution of your PL/SQL bloc# or subprogram
stops and control transfers to its exception-handling part" which is formatted as
shown on the slide.
Predefined Exceptions syntax!
!E/0+
. . .
E@'EP10+
$>E+ +*&(1(*5,+& 1>E+
statement1;
statement2.
$>E+ 1*-(+A*)$S 1>E+
statement1.
$>E+ 1>E)S 1>E+
statement1;
statement2;
statement3.
E+&.
1o catch raised exceptions" write exception handlers. Each handler consists of a
$>E+ clause" which specifies an exception" followed by a se?uence of statements
to be executed when that exception is raised.
1hese statements complete execution of the bloc# or subprogram. control does not
return to where the exception was raised. ther words" it cannot resume processing
where left off.
1he optional 1>E)S exception handler" which" if present" is always the last
handler in a bloc# or subprogram" acts as the handler for all exceptions that are not
named specifically. 1hus" a bloc# or subprogram can have only one 1>E)S
handler.
"ote! PL/SQL declares predefined exceptions in the S1(+&()& pac#age.
0t is a good idea to always handle the +*&(1(*5,+& and 1*-(+A*)$S
exceptions" which are the most common.
Predefined Exceptions in racle Server7
'() %*+,P%
"%- "%).%)(/-P/- (0
DECLARE
v_num1 integer := &sv_num1;
v_num2 integer := &sv_num2;
v_result number;
BEGIN
v_result := v_num1 / v_num2;
DB!_"#$%#$&%#$_LINE '(v_result: ())v_result*;
E+CE%$I"N
,-EN .ER"_DI/IDE $-EN
DB!_"#$%#$&%#$_LINE'(A number 01nn2t be 3ivi3e3 b4 5er2&(*;
END;
Enter value for sv*num=7 :
old <7 v*num= integer 7B Csv*num=.
new <7 v*num= integer 7B :.
Enter value for sv*num<7 8
old D7 v*num< integer 7B Csv*num<.
new D7 v*num< integer 7B 8.
( number cannot be divided by Eero.
PL/SQL procedure successfully completed.
&E'L()E
v*orderF +,-!E) 7B Csv*orderno.
v*ordered G()'>()<2D4 7B H+H.
!E/0+
&!-S*,1P,1.P,1*L0+E2H'hec# if the order has itemsH4.
SELE'1 HAESH 0+1 v*ordered 5)- orderitems $>E)E orderF B v*orderF.
&!-S*,1P,1.P,1*L0+E 2H1he order has one itemH4.
E@'EP10+
$>E+ +*&(1(*5,+& 1>E+
&!-S*,1P,1.P,1*L0+E 2H1he order is not foundH4.
$>E+ 1*-(+A*)$S 1>E+
&!-S*,1P,1.P,1*L0+E2H1he order has too many itemsH4.
E+&.
)esult 7
Enter value for sv*orderno7 =88I
'hec# if the order has items
1he order has too many items
PL/SQL procedure successfully completed.
&E'L()E
v*customer*no +,-!E) 7B Csv*cusomter*no.
v*customer*name G()'>()<2984.
!E/0+
SELE'1 firstnameJJH HJ J lastname 0+1 v*customer*name 5)- customers
$>E)E customerF B v*customer*no.
&!-S*,1P,1.P,1*L0+E 2Hcustomer name is HJJv*customer*name4.
E@'EP10+
$>E+ 1>E)S 1>E+
&!-S*,1P,1.P,1*L0+E 2H(n error has occurredH4.
E+&.
)esult7
Enter value for sv*cusomter*no7 =8=:
customer name is KE++05E) S-01>
PL/SQL procedure successfully completed.
Enter value for sv*cusomter*no7 =888
(n error has occurred
PL/SQL procedure successfully complete
Trapping "on predefined Oracle Serer Errors
1o trap a non predefined racle server error by declaring it first" or by using the
1>E)S handler. 1he declared exception is raised implicitly.
0n PL/SQL" the P)(/-( E@'EP10+*0+01 tells the compiler to associate an
exception name with an racle error number. 1hat allows to refer any internal
exception by name and to write a specific handler for it.
"ote! P)(/-( 2also called pseudoinstructions4 is the #eyword that signifies that
the statement is a compiler directive" which is not processed when the PL/SQL bloc#
is executed. )ather" it directs the PL/SQL compiler to interpret all occurrences of the
exception name within the bloc# as the associated racle server error number.
Example
&E50+E p*deptno B =8
&E'L()E
e*emps*remaining E@'EP10+.
P)(/-( E@'EP10+*0+01 2e*emps*remaining" -<<:<4.
!E/0+
&ELE1E 5)- dept $>E)E deptno B Cp*deptno.
'--01.
E@'EP10+
$>E+ e*emps*remaining 1>E+
&!-S*,1P,1.P,1*L0+E 2H'annot remove dept H JJ1*'>()2Cp*deptno4 JJ H.
Employees exist. H4.
E+&.
)esult7-
'annot remove dept =8. Employees exist.
PL/SQL procedure successfully completed.
=. &eclare the name for the exception within the declarative section.
Syntax
exception E@'EP10+.
where7 exception is the name of the exception.
<. (ssociate the declared exception with the standard racle server error number
using the P)(/-( E@'EP10+*0+01 statement.
Syntax
P)(/-( E@'EP10+*0+012exception, error_number).
where7 exception is the previously declared exception. error_number is a standard
racle Server error number.
D. )eference the declared exception within the corresponding exception-handling
routine.
0f there are employees in a department" print a message to the user that the
department cannot be removed.
#ro$ the preious exa$ple
1rap for racle server error number L<<:<" an integrity constraint violation. 1hat is
replaced with user defined new message for oracle error number2-<<:<4 . 1he
message cannot remove dept =8. Employees exist.
Error%Trapping #unctions
$hen an exception occurs" you can identify the associated error code or error
message by using two functions. !ased on the values of the code or message" you
can decide which subse?uent action to ta#e based on the error.
SQL'&E returns the number of the racle error for internal exceptions. Aou can
pass an error number to SQLE))-" which then returns the message associated
with the error number.
Example SQL'&E Galues
Example for trapping Error 'ode and Error -essage
&E'L()E
v*customer*no +,-!E) 7B Csv*cusomter*no.
v*customer*name G()'>()<2984.
v*error*code number.
v*error*message varchar<2<994.
!E/0+
SELE'1 firstnameJJH HJ J lastname 0+1 v*customer*name 5)- customers
$>E)E customerF B v*customer*no.
&!-S*,1P,1.P,1*L0+E 2Hcustomer name is HJJv*customer*name4.
E@'EP10+
$>E+ 1>E)S 1>E+
v_error_code := SQLCODE ;
v_error_message := SQLERRM ;
&!-S*,1P,1.P,1*L0+E 2H(n error has occurredHJJ Merror code is MJJ v*error*code
JJ M error message is MJJ v*error*message4.
E+&.

)esult 7 -
Enter value for sv*cusomter*no7 =888
(n error has occurrederror code is =88 error message is )(-8=;8D7 no data found
PL/SQL procedure successfully completed.
Trapping &ser%Defined Exceptions
( user-defined exception is an error that is defined by the programmer. 1he error
that it signifies is not necessarily an racle error. it could be an error with the data.
Predefined exceptions" on the other hand" correspond to common SQL and PL/SQL
errors.
$ou trap a user-defined exception by declaring it and raising it explicitly.
1. Declare the na&e for the user-defined exception within the declarative section.
Syntax7
exception EXCEPTION;
where2 exception is the na&e of the exception.
3. /se the )+4"% state&ent to raise the exception explicitly within the executable section.
"yntax2
RAISE exception;
where2 exception is the previously declared exception.
5. )eference the declared exception within the corresponding exception-handling routine.
Exa$ple for &ser defined exception7
&E'L()E
-- Exception to indicate an error condition
high*retail E@'EP10+.
v*error*code number.
v*error*message varchar<2<994.
v*retail boo#s.retailNtype.
!E/0+
SELE'1 retail into v*retail from boo#s
$>E)E title B HS>)1ES1 PE-SH.
/3 Ensure that there are no duplicates 3/
05 v*retail O <8 1>E+
)(0SE high*retail.
E+& 05.
E@'EP10+
$>E+ high*retail 1>E+
v*error*code 7B SQL'&E .
v*error*message 7B SQLE))- .
&!-S*,1P,1.P,1*L0+E 2H(n error has occurredHJJ Herror code is HJJ v*error*code
JJ H error message is HJJ v*error*message4.
0+SE)1 0+1 log*table 2loginfo4
G(L,ES 2Hshortest poems retail greater than P<8H4.
E+&.

)esult 7
(n error has occurred error code is = error message is ,ser-&efined Exception
PL/SQL procedure successfully completed.
The RAISE_APPLICATION_ERROR Procedure
Syntax!
raise_application_error (error_number,message[,{TRUE| FALSE}]);
,se the )(0SE*(PPL0'(10+*E))) procedure to communicate a predefined
exception interactively by returning a nonstandard error code and error message.
$ith )(0SE*(PPL0'(10+*E)))" 0t can report errors to application and avoid
returning unhandled exceptions.
0n the syntax7
Error_number - is a user-specified number for the exception between L<8888
and L<8:::.
message -is the user-specified message for the exception. 0t is a character
string up to <"8;Q bytes long.
1),E J 5(LSE is an optional !oolean parameter 20f 1),E" the error is placed on the
stac# of previous errors. 0f 5(LSE" the default" the error replaces all previous errors.4
)(0SE*(PPL0'(10+*E))) can be used in either 2or both4 the executable
section and the exception section of a PL/SQL program. 1he returned error is
consistent with how the racle server produces a predefined" non predefined" or
user-defined error. 1he 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