PL/SQL之例外

来源:互联网 发布:支付宝找回淘宝密码 编辑:程序博客网 时间:2024/06/05 22:34

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)关闭光标,释放资源和内存垃圾。
0 0
原创粉丝点击