Oracle笔记 七、PL/SQL 异常处理

来源:互联网 发布:moderntimes软件 编辑:程序博客网 时间:2024/06/05 07:45
--异常处理
declare
  sNum number := 0;
begin
  sNum := 5 / sNum;  
  dbms_output.put_line(sNum);
exception 
  when others then
    dbms_output.put_line('is Error!');
end;
 
--自定义异常
declare
       ex_custom_invaild_age exception; --自定义的异常myerr
       age int;
begin
     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;
 
--异常处理
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('Error');
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;
 
--异常日志处理
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;
      vErrMsg := SQLERRM;
      insert into errorLog values(seq_errorLog_id.nextval, vErrCode, vErrMsg, sysdate);
      commit;
end;
 
select * from errorLog;
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 唯品会衣服坏了怎么办 京东买电视拆机坏的怎么办 余额宝资金冻结怎么办? 余额宝金额冻结怎么办 adidas买了假货怎么办 余额宝冻结金额怎么办 买到不合格地板怎么办 买到翻新地板怎么办 食品里有头发怎么办 家具环保不达标怎么办 买到坏了的食物怎么办 空调检测不合格的怎么办 淘宝卖精仿遇到打假怎么办? 没有收到提货码怎么办 增值税发票超过180天怎么办 花呗借钱还不上怎么办 实体店里没人气怎么办 EMS快件无人签收怎么办 邮政快递丢失了怎么办 快递手机丢了怎么办 拍照签收没收到怎么办 拼多多开店货源怎么办 被购买鉴定投诉怎么办 淘宝上买东西错想用花呗怎么办 淘宝想用花呗买东西差一点怎么办 买了假货怎么办还用吗 免税店买完东西怎么办 淘宝恶意拍单怎么办 二手西服不想要怎么办 苹果8p费电快怎么办 赌博被骗没证据怎么办 异地车子办保险怎么办 淘宝买到旧货怎么办 苹果官网买手机发票怎么办 车子异地换牌照怎么办 汽车异地上保险怎么办 后悔买保险了怎么办 平安run不计步怎么办 天梭力洛克有划痕怎么办 天梭手按钮坏了怎么办 天梭机械表总慢怎么办