例外:
例外是程序设计语言提供的一种功能,用来增加程序的健壮性和容错性。
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;
/