例外处理
例外的分类
- 预定义例外
用于处理常见的oracle错误 - 非预定义例外
用于处理预定义例外不能处理的例外 - 自定义例外
用于处理与oracle错误无关的其它情况
例外传递
declare
v_name emp.ename%type;
begin
select ename into v_name from emp where empno=&no;
dbms_output.put_line('名字:'||v_name);
exception--预定义例外
when no_data_found then
dbms_output.put_line('编号没有');
end;
/
处理预定义例外
是由pl/sql所提供的系统例外
当pl/sql应用程序违反了oracle规定的限制时,则会隐含的触发一个内部例外
case_not_found
在开发pl/sql块中编写case语句时,如果在when子句中没有包含必须的条件分支就会触发此例外
create procedure sp_pro7(spno number) is
v_sal emp.sal%type;
begin
select sal into v_sal from emp where empno=spno;
case
when v_sal<1000 then
update emp set sal=sal+100 where empno=spno;
when v_sal<2000 then
update emp set sal=sal+200 where empno=spno;
end case;
exception
when case_not_found then
dbms_output.put_line('case语句没有与'||v_sal||'相匹配的条件');
end;
/
cursor_already_open
当重新打开已经打开的游标时,会隐含的触发例外
declare
cursor emp_cursor is select ename,sal from emp;
begin
open emp_cursor;
for emp_record1 in emp_cursor loop
dbms_output.put_line(emp_record1.ename);
end loop;
exception
when cursor_already_open then
dbms_output.put_line('游标已经打开');
end;
/
dup_val_on_index
在唯一索引所对应的列上插入重复的值时,会隐含的触发例外
begin
insert into dept values(10,'公安部','北京');
exception
when dup_val_on_index then
dbms_output.put_line ('在deptno列上不能出现重复值');
end;
invalid_cursor
当试图在不合法的游标上执行操作时,会触发该例外
--例如:视图从没有打开的游标提取数据,或是关闭没有打开的游标
declare
cursor emp_cursor is select ename,sal from emp;
emp_record emp_cursor%rowtype;
begin
open emp_cursor;
fetch emp_cursor into emp_record;
dbms_output.put_line(emp_record.ename);
close emp_cursor;
exception
when invalid_cursor then
dbms_output.put_line('请检测游标是否打开');
end;
invalid_number
当输入的数据有误时,会触发该意外
--例如:数据100写成了1oo,就会触发该意外
begin
update emp set sal=sal+'1oo';
exception
when invalid_number then
dbms_output.put_line('输入的数字不正确');
end;
no_data_found
比如执行select into语句没有返回行,就会触发该例外
too_many_rows
当执行select into语句时,如果返回超过了一行,则会触发该例外
declare
v_ename emp.ename%type;
begin
select ename into v_ename from emp;
exception
when too_many_rows then
dbms_output.put_line('返回了多行');
end;
/
zero_divide
当执行2/0语句时,触发该意外(分母不为0)
value_error
当执行赋值操作时,如果变量的长度不足以容纳实际数据,则触发该例外
declare
v_ename varchar2(5);
begin
select ename into v_ename from emp where empno=&no;
dbms_output.put_line(v_ename);
exception
when value_error then
dbms_output.put_line('变量尺寸不足');
end;
/
其它预定义例外
login_devide
当用户非法登陆时,触发该例外
not_logged_on
如果用户没有登陆就执行dml操作,触发该例外
storage_error
如果超出了内存空间或内存被损坏,触发该例外
timeout_on_resource
如果oracle在等待资源时,出现了超时则触发该例外
处理自定义例外
自定义例外与oracle错误没有任何关联
它是由开发人员为特定情况所定义的例外
--编写一个pl/sql块,接收一个雇员的编号,并给该雇员工资增加1000元;如果该雇员不存在,请提示
create procedure ex_test(spno number) is
myex exception;
begin
update emp set sal=sal+1000
where emono=spno;
if sql%notfound then --表示没有update
raise myex;--触发myex
end if;
exception
when myex then
dbms_output.put_line('没有更新任何用户');
end;
/