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;

猜你喜欢

转载自www.cnblogs.com/Zs-book1/p/11228395.html