Oracle之例外(异常)

/*
   例外  其实就是异常
         处理发生的异常
         java try{}catch(OutofBoundIndexException){}catch(Exception e){}
         数据库对异常的处理
         exception
             when 异常类型 then
                 处理语句
         数据库异常分类  运行时异常 编译时异常 ClassCast ClassNotFound
                  系统定义异常
                      除数为0
                      赋值错误  类型转换错误
                     
                  自定义异常
                     使用场景:是不满足某些特定业务场景
                     java new 自定义类 继承Exception errorCode errorMsg
                  数据库
                     dept_no_emp  exception  --声明变量 类型为异常类型
                     raise dept_no_emp
       
*/
--除数为零  zero_divide
--类型转换  把字符串赋值给数值
declare
   v_n number :=0;
   v_m number :=1;
begin
   v_n := 'ss';
   v_m:=v_m/v_n;
exception
   when value_error   then
      dbms_output.put_line('赋值错误');
   when zero_divide   then
      dbms_output.put_line('除数不能为0');
   when others   then    --others 代表最大范围的异常  Exception
     dbms_output.put_line('出现异常');
end;

--太多记录数
declare 
     emp_row   emp%rowtype;     --记录类型变量
begin 
     select * into emp_row from emp;   
exception
    when too_many_rows then
      dbms_output.put_line('太多记录数请使用游标');
end;
---自定义异常 数据库不报错 不满足业务场景
--使用游标查询40号部门的员工信息 如果没有员工提示我 招人
declare
    cursor emp_cursor(dno number) is select * from emp where deptno=dno;  --声明游标
    emp_row emp%rowtype; --记录类型用于接收游标提取
    dept_no_emp exception; --声明自定义异常
begin
    open emp_cursor(40); --打开游标
    fetch emp_cursor into emp_row;  --保证先提取再判断
    if emp_cursor%notfound then 
      --没有员工 抛出异常
      raise dept_no_emp;
    end if;
    close emp_cursor;--关闭游标
exception
    when dept_no_emp then
      dbms_output.put_line('部门没有员工,快点招人');
end;

posted on 2017-12-20 09:39  一只小小小兔兔  阅读(557)  评论(0编辑  收藏  举报

导航