Exceptions 2020
Exceptions 2020
Errors
• Two types of errors can be found in a program:
compilation errors and runtime errors.
• There is a special section in a PL/SQL block that handles
the runtime errors.
• This section is called the exception-handling section, and
in it, runtime errors are referred to as exceptions.
• The exception-handling section allows programmers to
specify what actions should be taken when a specific
exception occurs.
Exception Handling
Exp5.sql
Using OTHERS Exception
OTHERS exception takes care of any other exception
raised apart from the defined exceptions in the
DECLARE
ENO EMP.EMPNO%TYPE;
salary emp.sal%type;
BEGIN
ENO:=&ENO;
SELECT SAL INTO SALARY FROM EMP WHERE
EMPNO=ENO;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE ('Some Error occurred ...');
END;
/
Using System Defined Numbered Exception
Assume that following table is created with check
constraint on supplier_id.
CREATE TABLE suppliers
( supplier_id number(4), supplier_name varchar2(50),
CONSTRAINT check_supplier_id
CHECK (supplier_id BETWEEN 100 and 9999)
);
BEGIN
insert into emp1(empno, Bdate) vALUES(9007,TO_DATE('10-41-
2018','DD-MM-YYYY'));
EXCEPTION
WHEN MONTH_Range THEN
dbms_output.put_line('Valid values for Month is 1 to 12');
END;
/
Example
--outer block
DECLARE
e_exception1 EXCEPTION;
e_exception2 EXCEPTION;
BEGIN
-- inner block
BEGIN
RAISE e_exception1;
EXCEPTION
WHEN e_exception1
THEN
RAISE e_exception2;
Example contd.
WHEN e_exception2
THEN
DBMS_OUTPUT.PUT_LINE (‘An error has occurred
in the inner’|| ‘block’);
END;
EXCEPTION
WHEN e_exception2
THEN
DBMS_OUTPUT.PUT_LINE (‘An error has occurred in the
program’);
END;
Example
Write a PL/SQL block to accept, Principle, Interest rate and duration
(in years) to calculate Interest to be paid. Handle the exceptions if
Principle <=1000, interest rate <5, year <1 and display proper error
message for each.