PLSQL学习——例外

例外:

例外是程序设计语言提供的一种功能,用来增加程序的健壮性和容错性。

Oracle中的例外:

系统例外:

No_data_found(没有找到数据)

--系统例外:no_data_found
set serveroutput on
declare
  pename emp.ename%type;
begin
  --查询员工号是1234的员工的姓名
  select ename into pename from emp where empno=1234;
  
  exception
  when no_data_found then dbms_output.put_line('没有找到该员工');
  when others then dbms_output.put_line('其他例外');
end;
/

Too_many_rows  (select ... into 语句匹配多个行)

--系统例外:too_many_rows
set serveroutput on

declare
  --定义变量
  pename emp.ename%type;
begin
  --查询所有10号部门的员工姓名
  select ename into pename from emp where deptno=10;
  exception
  when too_many_rows then dbms_output.put_line('select into 匹配了多行');
  when others then dbms_output.put_line('其他例外');
end;
/

Zero_Divide(被零除)

--系统例外:被0除  zero_divide
set serveroutput on
declare
  --定义一个基本变量
  pnum number;
begin
  pnum := 1/0;
exception
  when zero_divide then dbms_output.put_line('1:0不能做被除数');
                        dbms_output.put_line('2:0不能做被除数');
  when others then dbms_output.put_line('其他例外');
end;
/


Value_error (算数或转换错误)

--系统例外:value_error
set serveroutput on
declare
  --定义一个number类型的变量
  pnum number;
begin
  pnum := 'abc';
exception
  when value_error then dbms_output.put_line('算术或者转换错误');
  when others then dbms_output.put_line('其他例外');
end;
/

Timeout_on_resource(在等待资源时发生超时)

自定义例外:

  • 定义变量,类型是exception
  • 使用raise抛出自定义例外

--自定义例外:查询50号部门的员工姓名
set serveroutput on
declare
  --定义光标,代表50号部门的员工姓名
  cursor cemp is select ename from emp where deptno=50;
  pename emp.ename%type;
  
  --自定义例外
  no_emp_found exception;

begin
  --打开光标
  open cemp;
  
  --直接取一个员工的姓名
  fetch cemp into pename;
  if cemp%notfound then
    --抛出例外
    raise no_emp_found;
  end if;
  
  --关闭光标
  --oracle自动启动pmon(process monitor)
  close cemp;
  
exception
  when no_emp_found then dbms_output.put_line('没有找到员工');
  when others then dbms_output.put_line('其他例外');
end;
/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上善若水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值