PLSQL-异常处理

时间:2022-07-25
本文章向大家介绍PLSQL-异常处理,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

异常处理

加入异常处理的语句块结构

declare
    --声明变量
begin
   --程序体
exception
   --异常处理
end;

常见的异常

declare
  vSal emp.sal%type;
begin
  select sal into vSal from emp;
exception
    when too_many_rows then
      dbms_output.put_line('单一变量不能存放多条数据');
    when others then
      dbms_output.put_line('发生了异常');
end;
declare
  vSal emp.sal%type;
begin
  select sal into vSal from emp where empno = 1;
exception
    when no_data_found then
        dbms_output.put_line('查询结果没有数据');
    when others then
        dbms_output.put_line('Error');
end;

自定义异常

declare
     ex_custom_invaild_age exception; --自定义的异常
     age int;
begi
     age := &请输入年龄;
     if (age < 0) then
        raise ex_custom_invaild_age; --引发自定义异常
     else
        dbms_output.put_line('年龄是:' || age);
     end if;
exception
      when ex_custom_invaild_age then
        dbms_output.put_line('非法的年龄');
end;

引发应用程序异常

  • raise_application_error(异常编号,说明);
declare
       age int;
begin
     age := &请输入年龄;
     if (age < 0) then
        raise_application_error(-20500, '年龄只能是正整数');
     else
        dbms_output.put_line('年龄是:' || age);
     end if;
end;

非预定义异常

declare
     ex_custom_error exception;  --自定义异常
     pragma exception_init(ex_custom_error, -1); --把一个编号和一个自定义异常关联,
     --相当于把-1编号的异常命名为ex_custom_error,这样就可以捕获这种异常
begin
     insert into dept values(10, 'aaa', 'bbb');
exception
       when ex_custom_error then
        dbms_output.put_line('部门编号已经存在');

end;

异常日志处理

create table errorLog (

       id number primary key,

       errCode number,

       errMsg varchar2(1024),

       errDate date

);

--创建序列,从1开始,每次加1

create sequence seq_errorLog_id start with 1 increment by 1;


declare
       vDeptno dept.deptno%type := 10;
       vErrCode number;
       vErrMsg varchar2(1024);
begin
  delete from dept where deptno = vDeptno;
  commit;
exception
    when others then
      rollback;
      vErrCode := SQLCODE;  --SQL异常编号
      vErrMsg := SQLERRM;   --SQL异常信息
      --SQLCODE和SQLERRM为异常处理自带变量
      insert into errorLog values(seq_errorLog_id.nextval, vErrCode, vErrMsg, sysdate);
      commit;
end;



select * from errorLog

转载自

http://www.cnblogs.com/hoojo/archive/2011/05/03/2035350.html

喜欢 (1)or分享 (0)