最近写一些函数已近存储过程时经常用到捕获异常、抛出异常一类的问题,虽然网上有问多这方面的资料,单我这里只是按自己的理解去描述一下在orale中使用异常的方法:
一、抛异常:
. 通过PL/SQL运行时引擎
. 使用RAISE语句
. 调用RAISE_APPLICATION_ERROR存储过程
二、使用方法:
1.当数据库或PL/SQL在运行时发生错误时,一个异常被PL/SQL运行时引擎自动抛出,我们可以通过捕获异常获得异常信息
begin
exception
when others then
v_errorcode := -abs(sqlcode);
v_errormsg := sqlerrm;
end;
2. 用户手动抛异常
begin
select count(*) into v_count
from t_table
if v_count <= 0 then
raise NO_DATA_FOUND;
end if;
exception
when no_data_found then
v_errorcode := -1;
v_errormsg := '数据不存在!';
when others then
v_errorcode := -abs(sqlcode);
v_errormsg := sqlerrm;
end;
说明:在PL/SQL块的异常部分只有已命名的异常才能被WHEN子串处理,ORACLE包含了一系列已命名的异常,这些异常都声明在STANDARD包中。
3.RAISE_APPLICATION_ERROR
begin
select count(*) into v_count
from t_table
if v_count <= 0 then
raise_application_error(-20000,'自定义异常');
end if;
exception
when others then
v_errorcode := -abs(sqlcode);
v_errormsg := sqlerrm;
说明:此时的 sql sqlerrm 为 '自定义异常',其中 raise_application_error 第一个参数,异常代码号范围为 -20000~-20999
end;