PL SQL學習筆記 異常處理

2021-09-05 21:25:08 字數 1930 閱讀 9390

一:預定義異常錯誤

先看**:

declare 

mytitle labor.xland.title%type;

begin

select title into mytitle from labor.xland where state = 2;

dbms_output.put_line(mytitle);

exception

when no_data_found then

dbms_output.put_line('沒有找到資料');

end;

這段程式當檢索到資料的時候就輸出資料

檢索不到資料即輸出  沒有找到資料

no_data_found 是乙個預定義異常錯誤型別

更多預定義異常錯誤,請看:

二:非預定義異常錯誤

先看**:

declare 

v_sqlcode number;

v_sqlerrm varchar2(2048);

begin

insert into labor.xland values(null,'1111',1);

exception

when no_data_found then

dbms_output.put_line('沒有找到資料');

when others then

if sqlcode = -1400 then

v_sqlcode := sqlcode;

v_sqlerrm := sqlerrm;

dbms_output.put_line(to_char(v_sqlcode));

dbms_output.put_line(v_sqlerrm);

end if;

end;

when 塊不必跟end結束

if塊需跟end if結束

sqlcode為錯誤碼

sqlerrm為oracle反饋的錯誤資訊

此程式輸出:

-1400

ora-01400: 無法將 null 插入 ("labor"."xland"."title")

另外還有pragma exception_init(name,errcode)函式來處理非預定義異常

如:

declare 

v_exception exception;

pragma exception_init(v_exception,-1400);

begin

insert into labor.xland values(null,'1111',1);

exception

when no_data_found then

dbms_output.put_line('沒有找到資料');

when v_exception then

dbms_output.put_line('沒有找到資料1');

end;

這裡提到了乙個新的資料型別  exception

pragma exception_init(name,errcode)

把錯誤號為-1400的錯誤賦值給v_exception

在第二個when子句中不能使用sqlcode等系統變數

三:自定義異常並丟擲

先看**

declare 

v_exception exception;

begin

raise v_exception;

exception

when v_exception then

dbms_output.put_line('捕獲異常');

end;

先定義乙個異常

然後丟擲這個異常

然後捕獲這個異常

如此而已

pl sql異常處理

丟擲異常 oracle有三種型別的異常錯誤 1 預定義 predefined 異常 oracle預定義的異常情況大約有24個。對這種異常情況的處理,無需在程式中定義,由oracle自動將其引發。2 非預定義 predefined 異常 即其他標準的oracle錯誤。對這種異常情況的處理,需要使用者在...

PLSQL 異常處理

1.異常塊begin pl sql塊 exception when no data found then 沒有找到資料 響應命令 when too many rows then 返回多行,隱式游標每次只能檢索一行資料 響應命令 when invalid number then 字元向數字轉換失敗 響...

plsql異常處理

1.在plsql 中 形式引數和 where 語句中的引數不能一樣,否則的話就就會出現個中莫名其妙的錯誤。function validate import supplier p task seq in number,任務號 p line num in number,行號 p vendor name ...