| --第一种方式:使用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 进行捕捉了.但也不是所有的预定义异常都可以绑定,这个需要使用的时候自己多试试
 |