在java的程式設計中,我們經常會抛出各種各樣的異常,程式從上而下執行,當出現異常,而我們沒有處理時,就會報錯,程式就會終止運作,是以我們在java中使用throw和try/catch來處理異常資訊,pl/sql中将sql語句作為了一個程式塊,當出現了異常時,就會導緻整個程式塊不能運作,是以我們也需要對其進行異常處理。
在pl/sql中有三個類型的異常錯誤:
1.預定義錯誤
2.非預定義錯誤
3.使用者定義錯誤
異常處理部分通常放在程式塊的後半部分,結構為:
declare
begin
-- 程式塊
exception
when first_exception(異常名) then 異常處理語句;
when second_exception(異常名) then 異常處理語句;
when others then 異常處理語句;
end;
預定義錯誤:由oracle預定義的異常錯誤有24個,對這種異常情況的處理,無需在程式中定義,由oracle自動将其引發
對于以上異常情況的處理,直接引用異常名并進行處理即可。
舉例:
declare
v_row emp%rowtype;
begin
select * into v_row from emp where job='CLERK';
exception
when no_data_found then
dbms_output.put_line('表中沒有該資料');
when TOO_MANY_ROWS then
dbms_output.put_line('有多條資料');
when others then
dbms_output.put_line('111');
end;
2.非預定義異常的處理
對于這類異常情況的處理,必須首先對其定義,步驟如下:
1.在pl/sal塊的定義部分定義異常情況:
異常情況 EXCEPTION;
2.将定義好的異常情況與oracle錯誤聯系起來,使用exception_init語句:
PRAGMA EXCEPTION_INIT(<異常情況>, <錯誤代碼>);
3.在pl/sql的異常處理部分對異常情況做出相應的處理。
declare
dept_not_found exception ;
pragma exception_init (dept_not_found ,-2291);
begin
update emp set deptno=90 where empno=7788;
exception
when dept_not_found then
dbms_output.put_line('該部門不存在');
end;
3.使用者自定義錯誤
declare
empno_not_found exception ;
begin
delete from emp where empno=987987;
if sql%notfound then
raise empno_not_found;
end if;
exception
when empno_not_found then
dbms_output.put_line('找不到該員工');
end;