--第一種方式:使用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 進行捕捉了.但也不是所有的預定義異常都可以綁定,這個需要使用的時候自己多試試