PL/SQL之例外

1.例外的概念

在oracle中錯誤被叫做例外:分爲系統例外和自定義例外。

2.系統例外

No_data_found(沒有找到數據)、Too_many_rows(select ... into 語句匹配多個行)、Zero_Divide(被零除)、Value_error(算數或轉換錯誤)、Timeout_on_resource(在等待資源時發生超時)

3. No_data_found

eg:

set serveroutput on

declare

 pename emp.ename%type;

begin

 select ename into pename from empwhere empno=1234;

exception

 when no_data_found thendbms_output.put_line('沒有找到該員工');

 when others thendbms_output.put_line('其他例外');

end;

/

4.Too_many_rows

eg:

set serveroutput on

declare

 pename emp.ename%type;

begin

 select ename into pename from empwhere deptno=10;

exception

 when too_many_rows thendbms_output.put_line('select into 匹配了多個行');

 when others thendbms_output.put_line('其他例外');

end;

/

5.Zero_Divide

eg:

set serveroutput on

declare

 pnum number;

begin

 pnum := 1/0;

exception

 when zero_divide thendbms_output.put_line('1:0不能做被除數');

                      dbms_output.put_line('2:0不能做被除數');

 when others thendbms_output.put_line('其他例外');

end;

/

Tips:then相當於大括號,後邊可以有多個語句。

6.Value_error

eg:

set serveroutput on

declare

 pnum number;

begin

 pnum := 'abc';

exception

 when value_error thendbms_output.put_line('算數或者轉換錯誤');

 when others thendbms_output.put_line('其他錯誤');

end;

/

7.自定義例外

定義變量,類型是exception

使用raise拋出自定義例外

eg:

set serveroutput on

declare

 cursor cemp is select ename fromemp where deptno = 50;

 pename emp.ename%type;

 no_emp_found exception;

begin

 open cemp;

 fetch cemp into pename;

 if cemp%notfound then

  raise no_emp_found;

  end if;

  close cemp;

exception

 when no_emp_found thendbms_output.put_line('沒有找到員工');

 when others thendbms_output.put_line('其他例外');

end;

/

Tips: 此例子光標由於拋出異常沒有正確關閉,但是oracle有一種機制,啓動一個進程pmon(process monitor)關閉光標,釋放資源和內存垃圾。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章