PL/SQL异常

12 篇文章 0 订阅

PL/SQL异常

PL/SQL有两种类型的异常:

  • 内置异常
  • 用户定义异常

内置异常

内置异常是隐式抛出的,当发生特定错误时,与该错误相关的内置异常就会抛出

declare
  dept_id   varchar2(10) := &d_ip;
  dept_name varchar2(20);

begin
  select name into dept_name from dept where id = dept_id;
  dbms_output.put_line('部门名称' || dept_name);

exception
  when no_data_found then
    dbms_output.put_line('没有这个部门ID'); 
end;

用户定义异常

用户定义异常:定义自己的异常及如何重新抛出异常,用户定义异常必须显式抛出。注意RAISE语句应该与IF语句一起使用。

declare
  dept_id   varchar2(10) := &d_ip;
  dept_name varchar2(20);
  e_invalid_id exception; --声明异常

begin
  --用户定义异常必须显式抛出,指明什么条件下抛出异常
  if dept_id < 0 then
    raise e_invalid_id;
  else
    select name into dept_name from dept where id = dept_id;
    dbms_output.put_line('部门名称' || dept_name);
  end if;
exception
  when no_data_found then
    dbms_output.put_line('没有这个部门ID');
  
  --异常处理部分与内置异常格式相同
  when e_invalid_id then
    dbms_output.put_line('这是无效的部门ID');
end;

RAISE_APPLICATION_ERROR

RAISE_APPLICATION_ERROR是oracle提供的一种特殊的内置过程,适用于未命名的用户定义异常,它负责把错误编号和错误文本关联起来。
语法 :

RAISE_APPLICATION_ERROR(error_number,error_message);
或者
RAISE_APPLICATION_ERROR(error_number,error_message,keep_errors);

参数说明:
error_number是与特定错误消息相关联的错误编号,这个编号的范围在-20999和-20000之间
error_message是错误文本,最多包含2048个字符
keep_errors是可选参数,如果keep_errors被设置为TRUE,新错误会被添加到已经抛出的错误列表中,这种错误列表被称为错误栈。如果是FALSE,新错误会替换已经抛出的错误栈,keep_errors参数默认是FALSE。

declare
  dept_id   varchar2(10) := &d_ip;
  dept_name varchar2(20);
  --e_invalid_id exception; --声明异常

begin
  
  if dept_id < 0 then
    raise_application_error (-20000,'这是无效的部门ID');
  else
    select name into dept_name from dept where id = dept_id;
    dbms_output.put_line('部门名称' || dept_name);
  end if;

end;

在这里插入图片描述

SQLCODE和SQLERRM

oracle提供两个内置函数——SQLCODE和SQLERRM,用于实现others异常处理程序,sqlcode函数会返回oracle错误编号,sqlerrm函数会返回错误消息,sqlerrm函数所返回消息的最大长度是512字节 。

declare
  dept_id   varchar2(10) := &d_ip;
  dept_name varchar2(20);

begin
  select name into dept_name from dept where id = dept_id;
  dbms_output.put_line('部门名称' || dept_name);

exception
  when no_data_found then
    dbms_output.put_line(SQLCODE||','||SQLERRM); 
end;
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值