您的位置:首页 > 数据库 > Oracle

(Oracle)异常处理的相关知识与实例

2011-11-20 17:13 351 查看
异常

还是用实例和注释来诠释吧!

实例1

查询empno=1234的雇员名字(emp表中无此雇员)

set serveroutput on

declare

v_ename emp.ename%type;

begin

select ename into v_ename from emp whereempno=1234;

dbms_output.put_line(v_ename);

exception --异常处理的标识,它位于begin之后

when no_data_found then --判断异常

dbms_output.put_line('雇员编号错误,没有找到相应雇员!'); --显示异常信息

when others then

dbms_output.put_line('未知错误!');

end;

实例2

自定义异常

set serveroutput on

declare

insert_error exception; --自定义异常insert_error

pragma exception_init(insert_error,-1400); --将自定义的异常insert_error与系统异常1400相关联

begin

insert into emp(empno) values(null); --注:emp表中empno为主键,空值是不允许的,所以会异常

exception --异常标识

when insert_error then --判断异常

dbms_output.put_line('不能插入空值!');

when others then

dbms_output.put_line('未知异常!');

end;

实例3

真正的自定义异常

set serveroutput on

declare

new_excep exception; --自定义异常new_excep

p_deptno emp.deptno%type;

cursor emp_cursor is select ename from emp where deptno=p_deptno;

v_ename emp.ename%type;

begin

p_deptno:=40; --通过改变它的值来实现程序的效果

open emp_cursor;

if p_deptno in(10,20,30) then

dbms_output.put_line('部门'||p_deptno||'的雇员:');

loop

fetch emp_cursor into v_ename;

exit when emp_cursor%notfound;

dbms_output.put_line(v_ename);

end loop;

else

raise new_excep; --触发异常new_excep

end if;

exception

when new_excep then --判断异常

dbms_output.put_line('部门不存在!');

when others then

dbms_output.put_line('未知异常!');

end;

实例4

使用raise_application_error 函数引发系统异常

set serveroutput on

declare

v_empno emp.empno%type;

begin

v_empno:=8888;

insert into emp(empno,ename)values(v_empno,'JACK');

if v_empno<7000 then

rollback;

raise_application_error(-20001,'编号小于7000'); --用函数引发系统异常

end if;

if v_empno>8000 then

rollback;

raise_application_error(-20001,'编号大于8000');

end if;

end;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: