oracle 自定义异常处理



--第一种方式:使用raise_application_error抛出自定义异常
declare
i number:=-1;
begin
if i=-1 then
raise_application_error(-20000,'参数值不能为负'); --抛出自定义异常
end if;
exception
when others then
dbms_output.put_line('err_code:'||sqlcode||';err_msg:'||sqlerrm); --进行异常处理
raise; --继续抛出该异常
end;

--第二种方式,使用 exception 进行异常的定义
declare
i number:=-1;
my_err exception; --自定义异常
PRAGMA EXCEPTION_INIT(my_err, -01476); --初始化异常(我理解就是将该异常绑定到某个错误代码上)
begin
if i=-1 then
raise my_err; --抛出自定义异常
end if;
exception
when my_err then --捕捉自定义异常
dbms_output.put_line('err_code:'||sqlcode||';err_msg:'||sqlerrm); --异常处理
raise; --继续抛出这个自定义异常
when others then --捕捉其它异常
dbms_output.put_line('err_code:'||sqlcode||';err_msg:'||sqlerrm); --异常处理
raise; --继续抛出异常
end;

第一种方式自定义异常的代码范围为:-20000到-20300
第二种方式的好处是,可以将自定义异常绑定到某上具体的预定义错误代码上,
如ORA-01476: divisor is equal to zero
这样我们就可以捕捉自定义异常而不需要用 others 进行捕捉了.但也不是所有的预定义异常都可以绑定,这个需要使用的时候自己多试试


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM