oracle学习笔记6:pl/sql异常错误处理

在java的编程中,我们经常会抛出各种各样的异常,程序从上而下执行,当出现异常,而我们没有处理时,就会报错,程序就会终止运行,因此我们在java中使用throw和try/catch来处理异常信息,pl/sql中将sql语句作为了一个程序块,当出现了异常时,就会导致整个程序块不能运行,因此我们也需要对其进行异常处理。

在pl/sql中有三个类型的异常错误:

1.预定义错误

2.非预定义错误

3.用户定义错误

异常处理部分通常放在程序块的后半部分,结构为:

declare
  begin
--   程序块
  exception
  when first_exception(异常名) then 异常处理语句;
  when second_exception(异常名) then 异常处理语句;
  when others then 异常处理语句;
end;
预定义错误:由oracle预定义的异常错误有24个,对这种异常情况的处理,无需在程序中定义,由oracle自动将其引发

对于以上异常情况的处理,直接引用异常名并进行处理即可。

举例:

declare
  v_row emp%rowtype;
  begin
  select * into v_row from emp where job='CLERK';
  exception
  when no_data_found then
  dbms_output.put_line('表中没有该数据');
  when TOO_MANY_ROWS then
  dbms_output.put_line('有多条数据');
  when others then
  dbms_output.put_line('111');
end;
2.非预定义异常的处理

对于这类异常情况的处理,必须首先对其定义,步骤如下:

1.在pl/sal块的定义部分定义异常情况:

异常情况 EXCEPTION;

2.将定义好的异常情况与oracle错误联系起来,使用exception_init语句:

PRAGMA EXCEPTION_INIT(<异常情况>, <错误代码>);

3.在pl/sql的异常处理部分对异常情况做出相应的处理。

举例说明:

declare
  dept_not_found exception ;
  pragma exception_init (dept_not_found ,-2291);
  begin
  update emp set deptno=90 where empno=7788;
  exception
  when dept_not_found then
  dbms_output.put_line('该部门不存在');
end;
3.用户自定义错误

用户可以自定义异常处理,举例:

declare
  empno_not_found exception ;
  begin
  delete from emp where empno=987987;
  if sql%notfound then
    raise empno_not_found;
  end if;
  exception
    when empno_not_found then
  dbms_output.put_line('找不到该员工');
end;

 

转载于:https://www.cnblogs.com/Zs-book1/p/11228395.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值