Exception Handling in PLSQL
Exception Handling in PLSQL
* It ensures that your PL/SQL program can handle unexpected situations and
provides error messages or executing alternative logic when an error occurs.
Types of Exceptions:
--------------------
Predefined Exceptions:
----------------------
Oracle provides a set of predefined exceptions for common errors, such as
NO_DATA_FOUND or ZERO_DIVIDE.
User-Defined Exceptions:
-------------------------
You can define your own exceptions for specific error conditions that are not
covered by predefined exceptions.
TOO_MANY_ROWS: Raised when a SELECT INTO statement returns more than one row.
BEGIN
-- Executable statements
EXCEPTION
WHEN exception_name_1 THEN
-- Handling code for exception 1
WHEN exception_name_2 THEN
-- Handling code for exception 2
WHEN OTHERS THEN
-- Handling code for all other exceptions
END;
ex:
declare
salary number;
begin
select salary into salary from emp where deptid=12;
dbms_output.put_line(salary);
exception
when NO_DATA_FOUND then
dbms_output.put_line('No salary found for given deptid');
end;
/
declare
salary number;
begin
select salary into salary from emp where deptid=11;
dbms_output.put_line(salary);
exception
when NO_DATA_FOUND then
dbms_output.put_line('No salary found for given deptid');
when TOO_MANY_ROWS then
dbms_output.put_line('Too many rows for given Deptid');
end;
/
declare
salary number;
did number;
begin
did:=&deptid;
select salary into salary from emp where deptid=did;
dbms_output.put_line(salary/0);
exception
when NO_DATA_FOUND then
dbms_output.put_line('No salary found for given deptid');
when TOO_MANY_ROWS then
dbms_output.put_line('Too many rows for given Deptid');
when OTHERS then
dbms_output.put_line('PLSQL Exception found');
end;
/
User-defined exceptions:
* variable must be exception type to become an exception.
ex:
declare
INVALID_SALARY exception;
salary number;
begin
salary:=&salary;
if salary<15000 then
raise INVALID_SALARY;
else
dbms_output.put_line('you can apply for a loan');
end if;
exception
when INVALID_SALARY then
RAISE_APPLICATION_ERROR(-20002,'salary must be above 15000');
end;
/
raise -> keyword used to raise an user defined or predefined exception manually.
syntax:
raise exception_name;