8.PL/SQL异常处理

语法结构

declare
--声明部分
begin
--执行部分
exception
--异常部分
when  exception1 then 
--异常1处理程序
[when exception2  then 
--异常2处理程序 ]
[when others then 
--其它异常处理程序 ]
end;

语法解析
1、exception是异常处理部分开始的标志。

2、when后面是跟着异常的名称, then后面是对应异常处理程序。也就是当异常exception1出现时,执行的是异常1处理程序。其它异常程序不会进入。

3、when others then 指的是异常再前面异常捕获中未捕获到对应的异常处理程序,则全部进入其它异常处理程序进行异常处理。

1.预定义异常

Oracle一共提供了25种预定义异常名称

select *  from dba_source t where t.TEXT like '%EXCEPTION_INIT%' AND NAME='STANDARD';

案例:测试预定义异常

declare
ls_stuinfo stuinfo%rowtype;
begin
  select t.* into ls_stuinfo
    from stuinfo t
   where t.stuid='SC2018010061';
   --该学号找不到对应的学生 
exception
  when no_data_found  then
     dbms_output.put_line('该学生在学生信息表中找不到');
end;

2.非预定义异常

定义非预定义异常,可以分为两步走:

  1. 进行异常声明:声明一个异常名称
  2. 进行异常名称和错误编号关联

案例:演示非预定义异常的编写

declare
  ex_only exception;--声明一个异常名称
  PRAGMA EXCEPTION_INIT(ex_only,-00001);--主键唯一性错误
begin
   update  stuinfo t set t.stuid='SC201801005'     
   where t.stuid='SC201801006'; 
exception
  --捕获异常
  when ex_only  then
     dbms_output.put_line('该学号已经存在,不应许修改');
  when others then 
     dbms_output.put_line(sqlerrm);  
end;

3.自定义异常

进行自定义异常的步骤:
1.异常声明定义:在PL/SQL块的声明部分采用关键字exception定义异常名称
2.异常主动抛出:在PL/SQL块中执行部分,通过逻辑控制,主动使用raise关键字抛出异常,交给异常处理模块处理

案例:自定义异常演示

declare
  ex_check_sex exception;--声明一个异常名称
  ls_sex stuinfo.sex%type;
begin
   select t.sex into ls_sex from stuinfo t where t.stuid = 'SC201801006';
   dbms_output.put_line('该学生的性别是:'||ls_sex);--1:男,2:女
   if ls_sex not in ('1','2') then
     --性别不是1或者2主动抛出异常 
     raise ex_check_sex;
   end if;       
  
exception
  --捕获异常
  when ex_check_sex  then
     dbms_output.put_line('性别只能是男或者女');
  when others then 
     dbms_output.put_line(sqlerrm);  
end;
posted @ 2022-12-15 17:17  种太阳  阅读(87)  评论(0)    收藏  举报