自定义例外是指由pl/sql开发人员所定义的例外。预定义例外和非预定义例外都和oracle错误有关,并且出现oracle错误时会隐含的处罚相应例外;而自定义例外与oracle错误没有任何关联,它是由开发人员为特定情况所定义的例外。 看一看以下pl/sql块的运行。 decla
自定义例外是指由pl/sql开发人员所定义的例外。预定义例外和非预定义例外都和oracle错误有关,并且出现oracle错误时会隐含的处罚相应例外;而自定义例外与oracle错误没有任何关联,它是由开发人员为特定情况所定义的例外。
看一看以下pl/sql块的运行。
declare e_integrity exception; pragma exception_init(e_integrity,-2291);begin update emp set deptno=&dno where empno=&eno;exception when e_integrity then dbms_output.put_line('该部门不存在'); end;
使用例外函数:
1、sqlcode 和sqlerrm
sqlcode用于返回oracle错误号,而sqlerrm则用于返回错误号所对应的错误消息。为了在pl/sql应用程序中处理其他未预料到的oracle错误,用户可以在例外处理部分的when others 子句后引用这两个函数,以取得相关的oracle错误.示例如下:
declare v_ename emp.ename%type;begin select ename into v_ename from emp where sal=&v_sal; dbms_output.put_line('雇员名:'||v_ename); exception when no_data_found then dbms_output.put_line('不存在工资为'||&v_sal||'的雇员'); when others then dbms_output.put_line('错误号:'||sqlcode); dbms_output.put_line(sqlerrm); end;
当输入v_sal:1250时。
错误号:-1422ora-01422: 实际返回的行数超出请求的行数
2. raise_application_error
该函数用于在pl/sql应用程序中自定义错误消息。注意该过程只能在数据端的子过程(过程、函数、包、触发器)中使用,而不能在匿名块和客户端的子程序中使用,使用该函数的语法如下:
raise_application_error(error_number,message[ , {true| false}]);
其中,error_number用于定义错误号,该错误号必须是在-20000至-20999之间的负整数;message用于指定错误消息,并且该消息的长度不能超过2048字节;第三个参数为可选参数,如果设置为ture,则该错误会放在先前错误的堆栈中;如果设置为false(默认值),则会替换先前所有的错误。使用该过程的示例如下:
create or replace procedure raise_comm (eno number, commission number )is v_comm emp.comm%type; begin select comm into v_comm from emp where empno=eno; if v_comm is null then raise_application_error(-20021,'该雇员无补助啊',true); end if;exception when no_data_found then dbms_output.put_line('该雇员不存在'); end;
call raise_comm(7900,100);
显示如下错误:
ora-20021: 该雇员无补助啊
ora-06512: 在 scott.raise_comm, line 13
上面出现的错误,会在异常栈中打印出来。
下面是本人认为比较不错的异常处理方式:
一般情况下,我们会把异常名和异常号进行绑定,可能就是你所想要的结果吧
declare vnumber number(4); biger exception; --异常名 pragma exception_init(biger,-20001); --异常名和异常号绑定 equal exception; pragma exception_init(equal,-20002); small exception; pragma exception_init(small,-20003);begin vnumber:=&vnumber; if vnumber >10 then raise_application_error(-20001,'哈哈,大于10啊'); elsif vnumber = 10 then raise_application_error(-20002,'嗯,等于10...'); elsif vnumber
除了上面自定义的异常,我们还可以采用下面的这种方式定义异常
create or replace procedure pro_emp ( --- 多个用逗号隔开 v_eno in number ) is --------多个用分号隔开 v_max_id number; v_ename varchar2(10); v_raise exception; ---------定义一个异常begin select max(a.empno) into v_max_id from emp a; if v_eno >v_max_id then raise v_raise; ---遇到例外,执行这个异常,退出程序 进入到exception部分 end if; select ename into v_ename from emp where empno=v_eno; dbms_output.put_line('员工名称为:'||v_ename); exception when v_raise then ---------捕获v_raise异常 dbms_output.put_line('v_eno大于最大员工号'); /* raise_application_error(-20000,'v_id not exists'); */ when no_data_found then /* raise_application_error(-20011,'error:不存在');*/ dbms_output.put_line('没有获得有效数据'); end;