SlideShare a Scribd company logo
Database Lab
Swapnali Pawar
Predefined & User Defined
Exceptions
Swapnali Pawar
• An exception is an error condition during a program
execution.An error or a warning event is called an exception.
• Any abnormal condition or say event that interrupts the
normal flow of your program’s instructions at run time is an
exception. Or in simple words you can say an exception is a
run time error.
• Exceptions are designed for run time error handling rather
than compile time error handling. Errors that occur during
compilation phase are detected by the PL/SQL compiler and
reported back to the user.
What is an Exception?
Swapnali Pawar
Exceptions
Swapnali Pawar
Swapnali Pawar
Exception Handling
There are two types of PL/SQL exceptions in Oracle
database.
1. PreDefined / System-defined
Exceptions
2. User-Defined Exceptions
Types of Exceptions
Swapnali Pawar
• System-defined exceptions are defined and maintained
implicitly by the Oracle server.These exceptions are mainly
defined in the Oracle STANDARD package.Whenever an
exception occurs inside the program.The Oracle server
matches and identifies the appropriate exception from the
available set of exceptions.
• System defined exceptions majorly have a negative error code
and error message.These errors have a short name which is
used with the exception handler.
1. System-Defined Exceptions
Swapnali Pawar
Unlike System-Define Exception, User-Define Exceptions are
raised explicitly in the body of the PL/SQL block i.e more
specifically inside the BEGIN-END section)using the RAISE
Statement.
2. User-Define Exceptions
Swapnali Pawar
• If our code does not have an exception handling, then each
time we execute a statement, we must verify errors in
execution
.
• If we avoid exception handling in our code, the actual errors
get missed which gives rise to some other errors.
• The exception handling allows skipping multiple verifications
in the code.
• It provides better readability of the code by isolating the error
handlers in the code
Advantages Of Exception Handling
Swapnali Pawar
1. Pre-Defined Exception
• system defined exceptions are thrown by
default.
• Some of the popular System defined exceptions
are out of memory and division by
zero, having names like STORAGE_ERROR and
ZERO_DIVIDE respectively.
Swapnali Pawar
Exception
Oracle
Error
SQL
CODE
Description
ACCESS_INTO_NULL ORA - 06530 -6530 This exception is raised if a null object is naturally assigned a
value.
CASE_NOT_FOUND ORA - 06592 -6592 This exception is raised if none of the options in theWHEN
clause is chosen and there is no existence of an ELSE clause.
COLLECTION_IS_NULL ORA - 06531 -6531 This exception is raised when the code tries to apply collection
methods except EXISTS to a nested table or varray which is not
initialized. It can also be raised if our code tries to assign values
to a nested table or varray which is not initialized.
DUP_VAL_ON_INDEX ORA - 00001 -1 This exception is raised if duplicate values are tried to be stored
in a column that is constrained by a unique index.
CURSOR_ALREADY_OP
EN
ORA - 06511 -6511 This exception is raised if our code tries to open an already open
cursor.
INVALID_CURSOR ORA - 01001 -1001 This exception is raised if we try to do some operations on
cursors which are not permitted.For example, attempting to
close an already closed cursor.
INVALID_NUMBER ORA - 01722 -1722 This exception is raised if the conversion to a character string to
a number does not pass as the string is representing an invalid
number.
Pre-Defined Exception
Swapnali Pawar
Exception
Oracle
Error
SQL
CODE
Description
SYS_INVALID_ROWID ORA-01410 -1410 This exception is raised if the
conversion to a character string to a
universal row id does not pass as the
character string is representing an
invalid row id.
TIMEOUT_ON_RESOUR
CE
ORA-00051 -51 This exception is raised if Oracle is
waiting for a resource.
VALUE_ERROR ORA-06502 -6502 This exception is raised if a
mathematical, conversion, truncation
error happens in our program.
ZERO_DIVIDE ORA-01476 -1476 This exception is raised if we try to
divide a number by 0.
Swapnali Pawar
1. Pre-Defined Exception
Exceptions Defined by Oracle i.e System Defined
Exceptions-
1 . Zero_divide
2 . value_error
3 . Invalid_Number
4 . N0_Data_Found
5 . Too_Many_Rows
6 . Dup_Val_On_Index
7 . Cursor_Already_Open
8 . Invalid_Cursor
Swapnali Pawar
This Exception occurs if any number is divided by
Zero .
Eg-
a := &a; # 16
b := &b; # 0
c := a/b; # Occurs Divide_Zero
Exception
1. Zero_divide
Swapnali Pawar
2. Value_error
If Value Size exceeds or if data type is mismatched then
this exception occurs
A Number(3):=50000; # Exceeding 4 digit so
Value_Error Occurs
B Number(4):=‘Swapnali’ # DataType Missmatch
Value_Error Occurs
Swapnali Pawar
3. Invalid_Number
This exception occurs if invalid numeric arithmetic
operation is performed
Eg-
‘Swapnali’+10 # Invalid Arithmetic
Operation
Swapnali Pawar
4. No_Data_Found
This Exception occurs if data is not found inTable
N := &roll_no;
Select stud_name # No_Data_Found Exception
From Student
Where roll_no=N;
Swapnali Pawar
5. Too_Many_Rows
This exception occurs if select statement try to fetch
more than 1 record.
Eno := &deptno;
Select ename into EmpName
From employee
Where deptno=Eno;
If 10 records are there for select statement then select statement
fetches all 10 names & are assigned to EmpName but variable
EmpName takes only one at a time so too_many_rows exception
occurs
Swapnali Pawar
6. Dup_Val_On_Index
This exception Occurs if we try to insert duplicate
value in primary key column.
Eg-
Create table MyFriends (id number primary key , name varchar(30));
Insert into MyFriends id values(101);
Insert into MyFriends id values(101);
# 10 already exist in table so Dup_Val_On_Index exception occurs
Swapnali Pawar
7. Cursor_Already_Open
If you try to open cursor which is already open
without closing it then Cursor_Already_Open
exception occurs.
Open c1;
Open c1;
C1 is already open thus Cursor_Already_Open exception occurs.
Swapnali Pawar
8. Invalid_Cursor
If you try to open cursor which is no declared then
Invalid_Cursor exception occurs.
Open C1;
Cursor C1 is not declared & you try to open itThus
Invalid_Cursor exception occurs.
Swapnali Pawar
• User-defined exceptions are declared in a package, subprogram,
or within the declaration section of the PL/SQL block of code
and should be assigned names.
• Once an exception occurs, the natural flow of execution is
halted, and then the execution points to the exception section
of the PL/SQL code.
• User-defined ones have to be thrown explicitly by the RAISE
keyword.
• Thus the exception handling helps to deal with the errors that
are encountered during the run time execution and not while
compiling the program.
User-Defined Exception
Swapnali Pawar
1.Declare a variable of exception data type –
This variable is going to take the entire burden on its shoulders.
2.Raise the Exception –
This is the part where you tell the compiler about the condition
which will trigger the exception.
3.Handle the exception –
This is the last section where you specify what will happen
when the error which you raised will trigger
Steps for Exception Handling
Swapnali Pawar
User-Defined Exception
The developers can build their own exceptions and use them for
handling errors. They can be created in the declaration part of a
subprogram and can be accessed only inside that subprogram.
An exception that is created at the package level can be used
whenever the package is accessed. A user-defined exception can be
raised by using the RAISE keyword.
Syntax -
Declare
Exception_name Exception;
Here, the exception_n is the name of the exception that we are
raising. Thus we can declare an exception by giving a name followed
by the EXCEPTION keyword. An exception can be declared in a
similar manner like variables are declared. However, an exception is
an unexpected condition and not a data item.
Swapnali Pawar
Syntax for Exception Handling
DECLARE
<< declaration section >>
BEGIN
<<Block of executable code>>
IF conditionTHEN
RAISE exception_n;
END IF;
EXCEPTION
WHEN excp1THEN
<< excp1 handling block >>
WHEN excp2 THEN
<< excp2 handling block >>
........
WHEN othersTHEN
<< excp2 handling block>>
END;
The default exception is carried out with WHEN othersTHEN.
Swapnali Pawar
1. Raise Statement
2. Raise_Application_Error Statement
User-Defined Exception
When predefined exceptions don’t satisfy our requirement then
we define our own exception
Swapnali Pawar
1.Using Raise Statement-
Exception is raised using name.This statement is
used if you want to raise exception & also want
to handle it.
2. Using Raise_Application_Error
Statement-
Exception is raised using code.This statement is
used if you want to raise exception but don’t
want to handle it.
Swapnali Pawar
User-Defined Exception
Swapnali Pawar
1.To find sum of two
number:
set serveroutput on;
declare
a int;
b int;
c int;
begin
a:=&a;
b:=&b;
c:=a+b;
dbms_output.put_line('sum
of a and b'||c);
end;
2.To find greatest number among
two:
set serveroutput on
declare
a int;
b int;
c int;
begin
a:=&a;
b:=&b;
if(a>b)
then
dbms_output.put_line('a is greater');
else
dbms_output.put_line('b is greater');
end if;
end;
Declare
a number(2);
b number(2);
c number(4);
one_divide exception;
Begin
a:= &a;
b:= &b;
if b=1 then
raise one_divide;
end if ;
c:= a/b;
dbms_Output.put_line(c);
Exception
when zero_divide then
dbms_output.put_line('zero_Divide');
when one_divide then
dbms_output.put_line('one_divide');
when others then
dbms_output.put_line(sqlerrm);
End; /
Swapnali Pawar
Swapnali Pawar
2. Using Raise_Application_Error Statement-
Declare
vage number(10);
age number:=&vage;
Begin
if age < 18 then
Raise_Application_Error(-20008,'Age must be greater than 18 !');
end if;
dbms_output.put_line(‘Voting Allowed after completing 18 years');
Exception
when others then
dbms_output.put_line(sqlerrm);
End;
/
Swapnali Pawar
Swapnali Pawar
Example.
CREATETABLE CITIZEN (
ID INT NOT NULL,
NAMEVARCHAR (15) NOT NULL,
AGE INT NOT NULL,
PRIMARY KEY (ID)
);
We have created the CITIZEN table with the help of the SQL statement given below.
SELECT * FROM CITIZEN
Swapnali Pawar
Insert values to this table with SQL statements given below:
INSERT INTO CITIZENVALUES (1,‘Swapnali', 26);
INSERT INTO CITIZENVALUES (8,‘Rugveda', 15);
INSERT INTO CITIZENVALUES (5,‘Shree', 37);
Swapnali Pawar
Coding ImplementationWith Exception Handling:
DECLARE
citizen_id citizen.id%type;
citizen_name citizen.name%type;
citizen_age citizen.age%type := 9;
BEGIN
SELECT id, name INTO citizen_id, citizen_name
FROM citizen
WHERE age = citizen_age;
DBMS_OUTPUT.PUT_LINE ('Citizen id is: '|| citizen_id);
DBMS_OUTPUT.PUT_LINE ('Citizen name is: '|| citizen_name);
EXCEPTION
WHEN no_data_foundTHEN
dbms_output.put_line ('No citizen detail found');
WHEN othersTHEN
dbms_output.put_line ('Errors');
END;
/
Swapnali Pawar
Swapnali Pawar
Student Activity
1. Using Raise statement create user defined exception which raise
an error if sum of 2 numbers is greater than 5000.
2. Using Raise statement create user defined exception which raise
an exception if age <18 and displays ‘Your are not Allowed for
Voting This Year ! ’ Message.
3. Using Raise_Application_Error statement create your own
exception code for “Salary must be above 50000 for Loan
Approval !” message.
4. Create table with your name .Add columns Roll_no Name Marks
.Enter some records in table. Execute various queries on that table
& if records are not available raise no_data_found exception.
Swapnali Pawar

More Related Content

PPTX
PPT
Lect 1. introduction to programming languages
PPTX
Self exploration
PPTX
History of Computer
PPTX
Unit 4 plsql
PPTX
Linux operating system - Overview
PDF
Introduction to basic concepts of statistics
PPTX
SQL Joins.pptx
Lect 1. introduction to programming languages
Self exploration
History of Computer
Unit 4 plsql
Linux operating system - Overview
Introduction to basic concepts of statistics
SQL Joins.pptx

What's hot (20)

PPTX
Greedy Algorithm - Knapsack Problem
PPTX
PDF
JavaScript - Chapter 4 - Types and Statements
PPTX
JAVA AWT
PPTX
PPTX
This keyword in java
PDF
Java threads
PPTX
Packages in PL/SQL
PDF
Oops concepts || Object Oriented Programming Concepts in Java
PPTX
Inline function
PDF
Arrays in Java
PPTX
Segmentation in operating systems
PDF
Python recursion
PPTX
Control statements in java
PDF
Exception handling in plsql
PPTX
MULTI THREADING IN JAVA
PPTX
Methods in java
PPTX
Arrays in c
PPTX
String, string builder, string buffer
PPTX
Java basics and java variables
Greedy Algorithm - Knapsack Problem
JavaScript - Chapter 4 - Types and Statements
JAVA AWT
This keyword in java
Java threads
Packages in PL/SQL
Oops concepts || Object Oriented Programming Concepts in Java
Inline function
Arrays in Java
Segmentation in operating systems
Python recursion
Control statements in java
Exception handling in plsql
MULTI THREADING IN JAVA
Methods in java
Arrays in c
String, string builder, string buffer
Java basics and java variables
Ad

Similar to Exception Handling (20)

PPTX
7. exceptions handling in pl
PPTX
Exception
PPTX
Exception
PPT
Oracle PL/SQL exception handling
PPT
Les23[1]Handling Exceptions
PPTX
Introduction to java exceptions
PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
Plsql guide 2
PPTX
using Java Exception Handling in Java.pptx
PPT
04 Handling Exceptions
PPTX
Java SE 11 Exception Handling
PPTX
PL_SQL_1.pptx fvbxcfbhxdfgh .
PPTX
Exception and its handling mechanism.pptx
PPT
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
PPT
Exception handler
PPTX
Java Exceptions and Exception Handling
DOCX
Alerts in r12
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
PPT
Advanced_SQL_ISASasASasaASnjection (1).ppt
DOCX
VTU MCA 2022 JAVA Exceeption Handling.docx
7. exceptions handling in pl
Exception
Exception
Oracle PL/SQL exception handling
Les23[1]Handling Exceptions
Introduction to java exceptions
Ch-1_5.pdf this is java tutorials for all
Plsql guide 2
using Java Exception Handling in Java.pptx
04 Handling Exceptions
Java SE 11 Exception Handling
PL_SQL_1.pptx fvbxcfbhxdfgh .
Exception and its handling mechanism.pptx
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
Exception handler
Java Exceptions and Exception Handling
Alerts in r12
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Advanced_SQL_ISASasASasaASnjection (1).ppt
VTU MCA 2022 JAVA Exceeption Handling.docx
Ad

More from Swapnali Pawar (20)

PDF
Unit 3 introduction to android
PDF
Unit 1-Introduction to Mobile Computing
PDF
Unit 2.design mobile computing architecture
PDF
Introduction to ios
PDF
Fresher interview tips demo
PDF
View & index in SQL
PDF
Introduction to android
PDF
Android Introduction
PDF
SQL JOINS
PDF
Unit 2.design computing architecture 2.1
PDF
Unit 2 Design mobile computing architecture MC1514
PDF
Design computing architecture ~ Mobile Technologies
PDF
Mobile technology-Unit 1
PDF
Mobile Technology 3
PDF
Web Programming& Scripting Lab
PDF
Mobile Technology
PDF
Mobile Technology
PDF
Database Management System 1
PDF
web programming & scripting 2
PDF
web programming & scripting
Unit 3 introduction to android
Unit 1-Introduction to Mobile Computing
Unit 2.design mobile computing architecture
Introduction to ios
Fresher interview tips demo
View & index in SQL
Introduction to android
Android Introduction
SQL JOINS
Unit 2.design computing architecture 2.1
Unit 2 Design mobile computing architecture MC1514
Design computing architecture ~ Mobile Technologies
Mobile technology-Unit 1
Mobile Technology 3
Web Programming& Scripting Lab
Mobile Technology
Mobile Technology
Database Management System 1
web programming & scripting 2
web programming & scripting

Recently uploaded (20)

PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Sports Quiz easy sports quiz sports quiz
PDF
Complications of Minimal Access Surgery at WLH
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Basic Mud Logging Guide for educational purpose
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
01-Introduction-to-Information-Management.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial disease of the cardiovascular and lymphatic systems
O5-L3 Freight Transport Ops (International) V1.pdf
TR - Agricultural Crops Production NC III.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Cell Structure & Organelles in detailed.
Sports Quiz easy sports quiz sports quiz
Complications of Minimal Access Surgery at WLH
Anesthesia in Laparoscopic Surgery in India
VCE English Exam - Section C Student Revision Booklet
Final Presentation General Medicine 03-08-2024.pptx
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Basic Mud Logging Guide for educational purpose
STATICS OF THE RIGID BODIES Hibbelers.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Pharmacology of Heart Failure /Pharmacotherapy of CHF
human mycosis Human fungal infections are called human mycosis..pptx
Microbial diseases, their pathogenesis and prophylaxis
Abdominal Access Techniques with Prof. Dr. R K Mishra
01-Introduction-to-Information-Management.pdf

Exception Handling

  • 1. Database Lab Swapnali Pawar Predefined & User Defined Exceptions Swapnali Pawar
  • 2. • An exception is an error condition during a program execution.An error or a warning event is called an exception. • Any abnormal condition or say event that interrupts the normal flow of your program’s instructions at run time is an exception. Or in simple words you can say an exception is a run time error. • Exceptions are designed for run time error handling rather than compile time error handling. Errors that occur during compilation phase are detected by the PL/SQL compiler and reported back to the user. What is an Exception? Swapnali Pawar
  • 5. There are two types of PL/SQL exceptions in Oracle database. 1. PreDefined / System-defined Exceptions 2. User-Defined Exceptions Types of Exceptions Swapnali Pawar
  • 6. • System-defined exceptions are defined and maintained implicitly by the Oracle server.These exceptions are mainly defined in the Oracle STANDARD package.Whenever an exception occurs inside the program.The Oracle server matches and identifies the appropriate exception from the available set of exceptions. • System defined exceptions majorly have a negative error code and error message.These errors have a short name which is used with the exception handler. 1. System-Defined Exceptions Swapnali Pawar
  • 7. Unlike System-Define Exception, User-Define Exceptions are raised explicitly in the body of the PL/SQL block i.e more specifically inside the BEGIN-END section)using the RAISE Statement. 2. User-Define Exceptions Swapnali Pawar
  • 8. • If our code does not have an exception handling, then each time we execute a statement, we must verify errors in execution . • If we avoid exception handling in our code, the actual errors get missed which gives rise to some other errors. • The exception handling allows skipping multiple verifications in the code. • It provides better readability of the code by isolating the error handlers in the code Advantages Of Exception Handling Swapnali Pawar
  • 9. 1. Pre-Defined Exception • system defined exceptions are thrown by default. • Some of the popular System defined exceptions are out of memory and division by zero, having names like STORAGE_ERROR and ZERO_DIVIDE respectively. Swapnali Pawar
  • 10. Exception Oracle Error SQL CODE Description ACCESS_INTO_NULL ORA - 06530 -6530 This exception is raised if a null object is naturally assigned a value. CASE_NOT_FOUND ORA - 06592 -6592 This exception is raised if none of the options in theWHEN clause is chosen and there is no existence of an ELSE clause. COLLECTION_IS_NULL ORA - 06531 -6531 This exception is raised when the code tries to apply collection methods except EXISTS to a nested table or varray which is not initialized. It can also be raised if our code tries to assign values to a nested table or varray which is not initialized. DUP_VAL_ON_INDEX ORA - 00001 -1 This exception is raised if duplicate values are tried to be stored in a column that is constrained by a unique index. CURSOR_ALREADY_OP EN ORA - 06511 -6511 This exception is raised if our code tries to open an already open cursor. INVALID_CURSOR ORA - 01001 -1001 This exception is raised if we try to do some operations on cursors which are not permitted.For example, attempting to close an already closed cursor. INVALID_NUMBER ORA - 01722 -1722 This exception is raised if the conversion to a character string to a number does not pass as the string is representing an invalid number. Pre-Defined Exception Swapnali Pawar
  • 11. Exception Oracle Error SQL CODE Description SYS_INVALID_ROWID ORA-01410 -1410 This exception is raised if the conversion to a character string to a universal row id does not pass as the character string is representing an invalid row id. TIMEOUT_ON_RESOUR CE ORA-00051 -51 This exception is raised if Oracle is waiting for a resource. VALUE_ERROR ORA-06502 -6502 This exception is raised if a mathematical, conversion, truncation error happens in our program. ZERO_DIVIDE ORA-01476 -1476 This exception is raised if we try to divide a number by 0. Swapnali Pawar
  • 12. 1. Pre-Defined Exception Exceptions Defined by Oracle i.e System Defined Exceptions- 1 . Zero_divide 2 . value_error 3 . Invalid_Number 4 . N0_Data_Found 5 . Too_Many_Rows 6 . Dup_Val_On_Index 7 . Cursor_Already_Open 8 . Invalid_Cursor Swapnali Pawar
  • 13. This Exception occurs if any number is divided by Zero . Eg- a := &a; # 16 b := &b; # 0 c := a/b; # Occurs Divide_Zero Exception 1. Zero_divide Swapnali Pawar
  • 14. 2. Value_error If Value Size exceeds or if data type is mismatched then this exception occurs A Number(3):=50000; # Exceeding 4 digit so Value_Error Occurs B Number(4):=‘Swapnali’ # DataType Missmatch Value_Error Occurs Swapnali Pawar
  • 15. 3. Invalid_Number This exception occurs if invalid numeric arithmetic operation is performed Eg- ‘Swapnali’+10 # Invalid Arithmetic Operation Swapnali Pawar
  • 16. 4. No_Data_Found This Exception occurs if data is not found inTable N := &roll_no; Select stud_name # No_Data_Found Exception From Student Where roll_no=N; Swapnali Pawar
  • 17. 5. Too_Many_Rows This exception occurs if select statement try to fetch more than 1 record. Eno := &deptno; Select ename into EmpName From employee Where deptno=Eno; If 10 records are there for select statement then select statement fetches all 10 names & are assigned to EmpName but variable EmpName takes only one at a time so too_many_rows exception occurs Swapnali Pawar
  • 18. 6. Dup_Val_On_Index This exception Occurs if we try to insert duplicate value in primary key column. Eg- Create table MyFriends (id number primary key , name varchar(30)); Insert into MyFriends id values(101); Insert into MyFriends id values(101); # 10 already exist in table so Dup_Val_On_Index exception occurs Swapnali Pawar
  • 19. 7. Cursor_Already_Open If you try to open cursor which is already open without closing it then Cursor_Already_Open exception occurs. Open c1; Open c1; C1 is already open thus Cursor_Already_Open exception occurs. Swapnali Pawar
  • 20. 8. Invalid_Cursor If you try to open cursor which is no declared then Invalid_Cursor exception occurs. Open C1; Cursor C1 is not declared & you try to open itThus Invalid_Cursor exception occurs. Swapnali Pawar
  • 21. • User-defined exceptions are declared in a package, subprogram, or within the declaration section of the PL/SQL block of code and should be assigned names. • Once an exception occurs, the natural flow of execution is halted, and then the execution points to the exception section of the PL/SQL code. • User-defined ones have to be thrown explicitly by the RAISE keyword. • Thus the exception handling helps to deal with the errors that are encountered during the run time execution and not while compiling the program. User-Defined Exception Swapnali Pawar
  • 22. 1.Declare a variable of exception data type – This variable is going to take the entire burden on its shoulders. 2.Raise the Exception – This is the part where you tell the compiler about the condition which will trigger the exception. 3.Handle the exception – This is the last section where you specify what will happen when the error which you raised will trigger Steps for Exception Handling Swapnali Pawar
  • 23. User-Defined Exception The developers can build their own exceptions and use them for handling errors. They can be created in the declaration part of a subprogram and can be accessed only inside that subprogram. An exception that is created at the package level can be used whenever the package is accessed. A user-defined exception can be raised by using the RAISE keyword. Syntax - Declare Exception_name Exception; Here, the exception_n is the name of the exception that we are raising. Thus we can declare an exception by giving a name followed by the EXCEPTION keyword. An exception can be declared in a similar manner like variables are declared. However, an exception is an unexpected condition and not a data item. Swapnali Pawar
  • 24. Syntax for Exception Handling DECLARE << declaration section >> BEGIN <<Block of executable code>> IF conditionTHEN RAISE exception_n; END IF; EXCEPTION WHEN excp1THEN << excp1 handling block >> WHEN excp2 THEN << excp2 handling block >> ........ WHEN othersTHEN << excp2 handling block>> END; The default exception is carried out with WHEN othersTHEN. Swapnali Pawar
  • 25. 1. Raise Statement 2. Raise_Application_Error Statement User-Defined Exception When predefined exceptions don’t satisfy our requirement then we define our own exception Swapnali Pawar
  • 26. 1.Using Raise Statement- Exception is raised using name.This statement is used if you want to raise exception & also want to handle it. 2. Using Raise_Application_Error Statement- Exception is raised using code.This statement is used if you want to raise exception but don’t want to handle it. Swapnali Pawar User-Defined Exception
  • 27. Swapnali Pawar 1.To find sum of two number: set serveroutput on; declare a int; b int; c int; begin a:=&a; b:=&b; c:=a+b; dbms_output.put_line('sum of a and b'||c); end; 2.To find greatest number among two: set serveroutput on declare a int; b int; c int; begin a:=&a; b:=&b; if(a>b) then dbms_output.put_line('a is greater'); else dbms_output.put_line('b is greater'); end if; end;
  • 28. Declare a number(2); b number(2); c number(4); one_divide exception; Begin a:= &a; b:= &b; if b=1 then raise one_divide; end if ; c:= a/b; dbms_Output.put_line(c); Exception when zero_divide then dbms_output.put_line('zero_Divide'); when one_divide then dbms_output.put_line('one_divide'); when others then dbms_output.put_line(sqlerrm); End; / Swapnali Pawar
  • 30. 2. Using Raise_Application_Error Statement- Declare vage number(10); age number:=&vage; Begin if age < 18 then Raise_Application_Error(-20008,'Age must be greater than 18 !'); end if; dbms_output.put_line(‘Voting Allowed after completing 18 years'); Exception when others then dbms_output.put_line(sqlerrm); End; / Swapnali Pawar
  • 32. Example. CREATETABLE CITIZEN ( ID INT NOT NULL, NAMEVARCHAR (15) NOT NULL, AGE INT NOT NULL, PRIMARY KEY (ID) ); We have created the CITIZEN table with the help of the SQL statement given below. SELECT * FROM CITIZEN Swapnali Pawar Insert values to this table with SQL statements given below: INSERT INTO CITIZENVALUES (1,‘Swapnali', 26); INSERT INTO CITIZENVALUES (8,‘Rugveda', 15); INSERT INTO CITIZENVALUES (5,‘Shree', 37);
  • 33. Swapnali Pawar Coding ImplementationWith Exception Handling: DECLARE citizen_id citizen.id%type; citizen_name citizen.name%type; citizen_age citizen.age%type := 9; BEGIN SELECT id, name INTO citizen_id, citizen_name FROM citizen WHERE age = citizen_age; DBMS_OUTPUT.PUT_LINE ('Citizen id is: '|| citizen_id); DBMS_OUTPUT.PUT_LINE ('Citizen name is: '|| citizen_name); EXCEPTION WHEN no_data_foundTHEN dbms_output.put_line ('No citizen detail found'); WHEN othersTHEN dbms_output.put_line ('Errors'); END; /
  • 35. Swapnali Pawar Student Activity 1. Using Raise statement create user defined exception which raise an error if sum of 2 numbers is greater than 5000. 2. Using Raise statement create user defined exception which raise an exception if age <18 and displays ‘Your are not Allowed for Voting This Year ! ’ Message. 3. Using Raise_Application_Error statement create your own exception code for “Salary must be above 50000 for Loan Approval !” message. 4. Create table with your name .Add columns Roll_no Name Marks .Enter some records in table. Execute various queries on that table & if records are not available raise no_data_found exception.