• 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;
  • 相关阅读:
    springboot之mybatis别名的设置
    webstorm
    万字长文把 VSCode 打造成 C++ 开发利器
    残差residual VS 误差 error
    参数与非参数的机器学习算法
    阿里云产品梳理
    aws产品整理
    Azure产品整理
    OpenStack产品摘要
    头条、美团、滴滴、阿里、腾讯、百度、华为、京东职级体系及对应薪酬
  • 原文地址:https://www.cnblogs.com/Zs-book1/p/11228395.html
Copyright © 2020-2023  润新知