1. 程式人生 > 實用技巧 >Oracle 自定義異常處理

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