Ex No:8 Exception Handling Date
Ex No:8 Exception Handling Date
Date:
-------------------------------------------------------------------------------------------
Exception:
An exception is an error condition during a program execution. PL/SQL supports
programmers to catch such conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition. There are two types of exceptions −
System-defined exceptions
User-defined exceptions
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
exception3-handling-statements
........
exception3-handling-statements
END;
Creating table:
create table customers(id number,name varchar2(20));
c_id customers.id%type := 8;
c_name customerS.Name%type;
BEGIN
FROM customers
WHERE id = c_id;
EXCEPTION
dbms_output.put_line('Error!');
END;
Output:
PL/SQL procedure successfully completed.
Name:robert
No such customer!
Program:
DECLARE
c_id customers.id%type := 2;
c_name customerS.Name%type;
BEGIN
SELECT name INTO c_name
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN too_many_rows THEN
dbms_output.put_line('error trying to SELECT too many rows');
end;
Output:
PL/SQL procedure successfully completed.
a int:=10;
b int:=0;
answer int;
BEGIN
answer:=a/b;
exception
END;
Output:
dividing by zero please check the values again
the value of a is 10
the value of b is 0
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
statement;
END;
1.Raise keyword:
Program:
DECLARE
c_name customerS.Name%type;
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
FROM customers
WHERE id = c_id;
END IF;
EXCEPTION
dbms_output.put_line('Error!');
END;
Output:
PL/SQL procedure successfully completed.
No such customer!
Name: Robert
2. RAISE_APPLICATION_ERROR:
Program:
DECLARE
myex EXCEPTION;
n NUMBER :=&n;
BEGIN
dbms_output.put_line(i*i);
IF i*i=36 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
RAISE_APPLICATION_ERROR(-20015,’Number 36 reached’);
END;
Output:
PL/SQL procedure successfully completed.
16
25
36
49
Error report -
ORA-20015:Number 36 reached
ORA-06512: at line 15
Result:
Thus the SQL queries to perform exception handling was executed successfully and
the output is verified.