0% found this document useful (0 votes)
14 views8 pages

Exception Handling in PL

Pl sql

Uploaded by

asmalubnashaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Exception Handling in PL

Pl sql

Uploaded by

asmalubnashaikh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Exception Handling in PL/SQL

Exceptions are runtime errors or unexpected events that occur during the execution of a
PL/SQL code block.
The oracle engine is the first one to identify such an exception and it immediately tries to
resolve it by default exception handler.
The default exception handler is a block of code predefined in the memory to take the
appropriate action against exceptions.
Exception handling can be done in the EXCEPTION part of PL/SQL program code block.
Syntax:

DECLARE
-- Declaration statements;
BEGIN
-- SQL statements;
-- Procedural statements;
EXCEPTION
-- Exception handling statements;
END;

There are two types of exceptions:


1. System (pre-defined) Exceptions
2. User-defined Exceptions
 System (pre-defined) Exceptions
In order to handle common exceptions that occur while running PL/SQL code, there are two
types of exception handlers in oracle:
 Named Exception Handler
 Numbered Exception Handler
Named Exception Handling
Such exceptions are the predefined names given by oracle for those exceptions that occur
most commonly.
Syntax:
EXCEPTION
WHEN <exception_name> THEN
-- take action

Named Exception Meaning


Occurs when invalid username or invalid password is
LOGIN_DENIED
given while connecting to Oracle.
Occurs when select statement returns more than one
TOO_MANY_ROWS
row.
Occurs when invalid datatype or size is given by the
VALUE_ERROR
user.
NO_DATA_FOUND Occurs when no records are found.
Occurs when a unique constraint is applied on some
DUP_VAL_ON_INDEX column and execution of Insert or Update leads to
creation of duplicate records for that column.
PROGRAM_ERROR Occurs when internal error arise in program.
Occurs when the division of any variable value is
ZERO_DIVIDE
done by zero.

simple PL/SQL code block, to demonstrate the use of Named Exception Handler,
set serveroutput on;

DECLARE
a int;
b int;
c int;
BEGIN
a := &a;
b := &b;
c := a/b;
dbms_output.put_line('RESULT=' || c);
EXCEPTION
when ZERO_DIVIDE then
dbms_output.put_line('Division by 0 is not possible');
END;
Output:
Enter the value for a:10
Enter the value for b:0
Division by 0 is not possible
PL/SQL procedure successfully completed.

 User-defined Exception
In any program, there is a possibility that a number of errors can occur that may not be
considered as exceptions by oracle. In that case, an exception can be defined by the
programmer while writing the code such type of exceptions are called User-defined
exception.
User defined exceptions are in general defined to handle special cases where our code can
generate exception due to our code logic.
Syntax:
DECLARE

<exception name> EXCEPTION

BEGIN

<sql sentence>

If <test_condition> THEN

RAISE <exception_name>;

END IF;

EXCEPTION

WHEN <exception_name> THEN

-- some action

END;
Trigger:

Trigger is invoked by Oracle engine automatically whenever a specified event


occurs.Trigger is stored into database and invoked repeatedly, when specific condition
match.

Triggers are stored programs, which are automatically executed or fired when some
event occurs.

Triggers are written to be executed in response to any of the following events.

A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).

A database definition (DDL) statement (CREATE, ALTER, or DROP).


PL/SQL: Uses of Triggers
Here we have mentioned a few use cases where using triggers proves very helpful:
 Maintaining complex constraints which is either impossible or very difficult via
normal constraint(like primary, foreign, unique etc) applying technique.
 Recording the changes made on the table.
 Automatically generating primary key values.
 Prevent invalid transactions to occur.
 Granting authorization and providing security to database.
 Enforcing referential integrity.
Syntax:
CREATE OR REPLACE TRIGGER <trigger_name>

BEFORE/AFTER/INSTEAD OF

INSERT/DELETE/UPDATE ON <table_name>

REFERENCING (OLD AS O, NEW AS N)

FOR EACH ROW WHEN (test_condition)

DECLARE

-- Variable declaration;

BEGIN

-- Executable statements;

EXCEPTION

-- Error handling statements;

END <trigger_name>;

END;
CREATE OR REPLACE TRIGGER is a keyword used to create a trigger
and <trigger_name> is user-defined where a trigger can be given a name.
BEFORE/AFTER/INSTEAD OF specify the timing of the trigger's occurance. INSTEAD
OF is used when a view is created.
INSERT/UPDATE/DELETE specify the DML statement.
<table_name> specify the name of the table on which DML statement is to be applied.
REFERENCING is a keyword used to provide reference to old and new values for DML
statements.
FOR EACH ROW is the clause used to specify row level tigger.
WHEN is a clause used to specify condition to be applied and is only applicable for row-level
trigger.
DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code block
containing variable declaration, executable statements, error handling statements and marking
end of PL/SQL block respectively where DECLARE and EXCEPTION part are optional.

Example:
CREATE OR REPLACE TRIGGER CheckAge
BEFORE
INSERT OR UPDATE ON student
FOR EACH ROW
BEGIN
IF :new.Age>30 THEN
raise_application_error('Age should not be greater than 30');
END IF;
END;

Output:
Trigger is created.
ROLLNO SNAME AGE
11 Anu 20
12 Asha 21
13 Arpit 18
14 Chetan 20
15 Nihal 19

After initializing the trigger CheckAge, whenever we will insert any new values or update the
existing values in the above table STUDENT our trigger will check the age before
executing INSERT or UPDATE statements and according to the result of triggering
restriction or condition it will execute the statement.
Example 1:
INSERT into STUDENT values(16, 'Sai', 32, 'BCOM');
Output:
Age should not be greater than 30
Example 2:
INSERT into STUDENT values(17, 'Anu', 22, 'BCOM');
Output:
1 row created.

2) Example:
Creating a trigger:

Syntax
CREATE OR REPLACE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF}
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Consider a table - CUSTOMERS
ID NAME AGE ADDRESS
SALARY
1 Ramesh 23 Allahabad 20000
2 Suresh 22 Kanpur 22000
3 Mahesh 24 Ghaziabad 24000
4 Chandan 25 Noida 26000
5 Alex 21 Paris 28000
6 Sunita 20 Delhi 30000
Example:

Create trigger:

Let's take a program to create a row level trigger for the CUSTOMERS table that would fire for INSERT
or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the
salary difference between the old values and new values:

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0) DECLARE
sal_diff number; BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary:
' || :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff); END;
/

Output:
Trigger created.

You might also like