6. Concept of Error Handling- User Define Exception
6. Concept of Error Handling- User Define Exception
User-defined Exceptions
The technique that is used is to bind a numbered exception handler to a name using
Pragma Exception_init (). This binding of a numbered exception handler, to a name (i.e. a
String), is done in the Declare section of a PL/SQL block.
The Pragma action word is a call to a pre-compiler, which immediately binds the
numbered exception handler to a name when encountered.
The function Exception_init() takes two parameters the first is the user defined exception
name the second is the Oracle engine's exception number. These lines will be included in
the Declare section of the PL/SQL block.
The user defined exception name must be the statement that immediately precedes the
Pragma Exception_init() statement.
Syntax:
DECLARE
< ExceptionName > EXCEPTION ;
PRAGMA EXCEPTION_INIT (< ExceptionName >, <ErrorCodeNo>);
BEGIN
Using this technique it is possible to bind appropriate numbered exception handlers to
names and use these names in the Exception section of a PL/SQL block. When this is done
the default exception handling code of the exception handler is overridden and the user-
defined exception handling code is executed
Syntax:
DECLARE
< ExceptionName > EXCEPTION;
PRAGMA EXCEPTION_INIT (<ExceptionName>.<ErrorCodeNo>);
BEGIN
. . . .
EXCEPTION
WHEN < ExceptionName > THEN
< Action >
END;
Example:
SQL> -- create demo table
SQL> create table Employee8(
ID VARCHAR2(4 BYTE) notnull
,
First_Name VARCHAR2(10 BYTE),
Last_Name VARCHAR2(10 BYTE),
Start_Date DATE,
End_Date DATE,
Salary Number(8,2),
City VARCHAR2(10 BYTE),
Description VARCHAR2(15 BYTE)
)
/
SQL> DECLARE
e_MissingNull EXCEPTION;
PRAGMA EXCEPTION_INIT(e_MissingNull, -1400);
BEGIN
INSERT INTO Employee8 (id) VALUES (NULL);
EXCEPTION
WHEN e_MissingNull then
DBMS_OUTPUT.put_line('ORA-1400 occurred');
END;
/
ORA-1400 occurred
PL/SQL procedure successfully completed.
User Defined Exception Handling (For Business Rule Validations)
To trap business rules being violated the technique of raising user-defined exceptions
and then handling them, is used.
User-defined error conditions must be declared in the declarative part of any PL/SQL
block. In the executable part, a check for the condition that needs special attention is
made. If that condition exists, the call to the user-defined exception is made using a
RAISE statement. The exception once raised is then handled in the Exception handling
section of the PL/SQL code block.
Syntax:
DECLARE
<ExceptionName> Exception
BEGIN
<SQL Sentence >;
IF < Condition > THEN
RAISE <ExceptionName>;
END IF;
EXCEPTION
WHEN <ExceptionName>THEN {User Defined Action To Be Taken};
END;
The following example explains the usage of User-defined Exception