二十二、Oracle学习笔记:Oracle异常

一、Oralce异常
1.Oracle低层定义了很多异常,每个异常都有一个唯一的编码,这些异常之中,有一些是比较常见的,ORACLE
    给这些异常定义了名称,可以直接使用,其他没有名称只有编码的不能直接使用。
2.异常的分类
   (1)预定义异常
        既有编码又有名称的异常是预定义异常,此类异常可以直接使用
    (2)非预定义异常
        有编码但没有名称的异常是非预定义异常,此类异常不能直接使用,要想使用需要先声明一个异常名与代码绑定
    (3)自定义异常
        既没有编码也没有名称的异常时自定义异常,此类异常需要我们自己定义

3.异常的使用
 (1)预定义异常的使用

--格式:
  exception
    when 异常名 then
      --异常处理
--练习:使用too_many_rows预定义异常:多对一的情况,将一个字段多个值存入一个变量
  declare
    sal_a emp.sal%type;
  begin
    select sal into sal_a from emp;
    exception 
      when too_many_rows then
        dbms_output.put_line('多行对一行,出现异常');
  end;
  /
    


 (2)非预定义异常的使用

--格式:
  declare 
  --声明异常
    异常名 exception
  --绑定异常编码
    pragma exception_init(异常名,编码);
  begin
    exception
      when 异常名 then
        --异常处理
  end;
  /
            
--练习,使用-01407非预定义异常(此编码是修改主键为null发生的异常编码)
  declare 
  null_id exception;
  pragma exception_init(null_id,-01407);
  begin
    update emp set empno=null where empno=1001;
    exception
      when null_id then
         dbms_output.put_line('主键为空');
   end; 
  /

     
 (3)自定义异常的使用

--格式:
  declare
  --声明异常
  异常名 exception;
  begin
  --某条件发生时,抛出异常
  raise 异常名;
  exception
    when 异常名 then
      --异常处理
   end;
   /
--练习:定义进入浴池的年龄:大于18岁
  create or replace function isOrNot(age number)
  return number
  is
    age18 exception;
  begin
  if age<18 then 
    raise age18;    
  end if;
  return age;
  exception 
    when age18 then
      dbms_output.put_line('你不能进入浴池'); 
  return 0;   
  end;
       
  declare
    a number; 
   begin
     a:=isOrNot(16);
   end;
   /

猜你喜欢

转载自blog.csdn.net/qq_38741971/article/details/81429367
今日推荐