Wednesday, October 29, 2008

PL/SQL Exception - a simple test

Continue the effort to learn PL/SQL - This is about EXCEPTION, simple test.



denis@TEST10G> @exception_1
denis@TEST10G> rem This is the test case to test the following situation:
denis@TEST10G> rem
denis@TEST10G> rem 1. Not using any exception, which would result in an ORA-01403 error
denis@TEST10G> rem 2. Uisng predefined Oracle Database exception NO_DATA_FOUND
denis@TEST10G> rem 3. Using user-defined exception
denis@TEST10G> rem
denis@TEST10G>
denis@TEST10G>
denis@TEST10G> drop table t;

Table dropped.

denis@TEST10G>
denis@TEST10G> create table t
2 as
3 select
4 rownum empno,
5 a.object_name ename
6 from all_objects a
7 where rownum < 5000;

Table created.

denis@TEST10G>
denis@TEST10G>
denis@TEST10G> -- Case 1: exception not defined
denis@TEST10G>
denis@TEST10G> declare
2 emp_number integer :=5000;
3 emp_name varchar2(50);
4 begin
5 select ename into emp_name from t
6 where empno = emp_number; -- no such number
7 dbms_output.put_line('Employee name is ' || emp_name);
8 end;
9 /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 5


denis@TEST10G>
denis@TEST10G>
denis@TEST10G> -- Case 2: using predefind Oracle exception
denis@TEST10G>
denis@TEST10G> declare
2 emp_number integer :=5000;
3 emp_name varchar2(50);
4 begin
5 select ename into emp_name from t
6 where empno = emp_number; -- no such number
7 dbms_output.put_line('Employee name is ' || emp_name);
8 exception
9 when no_data_found then
10 dbms_output.put_line('No such employee:' || emp_number);
11 end;
12 /
No such employee:5000

PL/SQL procedure successfully completed.

denis@TEST10G>
denis@TEST10G>
denis@TEST10G> -- Case 3: using user-defined exception
denis@TEST10G> -- declare it in the delcaration part of a block
denis@TEST10G> -- define it in the exception part of the block
denis@TEST10G>
denis@TEST10G> declare
2 emp_number integer;
3 emp_name varchar2(50);
4 empno_out_of_range exception;
5 begin
6 emp_number := 5000;
7 if emp_number > 4999 or emp_number < 1 then
8 raise empno_out_of_range;
9 else
10 select ename into emp_name from t
11 where empno = emp_number;
12 dbms_output.put_line('Employee name is ' || emp_name);
13 end if;
14 exception
15 when empno_out_of_range then
16 dbms_output.put_line('Employee number:' || emp_number ||
17 ' is out of range.');
18 end;
19 /
Employee number:5000 is out of range.

PL/SQL procedure successfully completed.

No comments: