****************************
數據庫之【異常處理篇】
****************************
--預定義異常詳細列表
access_into_null 在未初化對象時出現
case_not_found 在CASE語句中的選項與用戶輸入的數據不匹配時出現
collection_is_null 在給尚未初始化的表或數組賦值時出現
cursor_already_open 在用戶試圖打開已經打開的遊標時出現
dup_val_on_index 在用戶試圖將重複的值存在使用唯一索引的數據庫列中時出現
invalid_cursor 在執行非法遊標運算(如打開一個尚未打開的遊標)時出現
invalid_number 在將字符串轉換爲數字時出現
login_denied 在輸入的用戶名或密碼無效時出現
no_data_found 在表中不存在的請求的行時出現,此外,當程序引用已經刪除的元素時
storage_error 在內存損壞或PL/SQL耗盡內存時出現
too_many_rows 在執行SELECT INTO語句後返回多行時出現
value_error 在產生大小限制錯誤時出現
zero_divide 以零作除數時出現
others 所有異常
-在PLSQL塊中,如果不使用錯誤捕獲,可以直接使用
raise_application_error(-20001,'工資太低');
--錯誤處理,-20001/*-20000到20999*/, '未指定項費率'/*2048字節*/,在語句執行部分使用,如果不是自定義錯誤的拋出,則不能與EXCEPTION一起使用
--如果要打印出所有錯誤信息:
dbms_output.put_LINE(SQLCODE||SQLERRM);
--SQLCODE錯誤編號
--SQLERRM錯誤信息
declare
--預定義錯誤(返回多行)
s_al number;
begin
select sal into s_al from emp;
exception
when too_many_rows then
dbms_output.put_line('返回多行');
end;
declare
--記錄沒找到
s_al number;
begin
select sal into s_al from emp where empno = 1;
exception
when no_data_found then
dbms_output.put_line('記錄沒找到');
end;
declare
--自定義錯誤
s_al number;
err exception;
begin
select sal into s_al from emp where empno = 7369;
if s_al < 3000 then
dbms_output.put_line(s_al);
raise err;
else
dbms_output.put_line(s_al);
end if;
exception
when err then
dbms_output.put_line('工資太低');
end;
--引發應用程序錯誤
declare
s_al number;
err exception; --定義錯誤
begin
select sal into s_al from emp where empno = 7369;
if s_al < 3000 then
dbms_output.put_line(s_al);
raise err; --拋出錯誤
else
dbms_output.put_line(s_al);
end if;
exception
--錯誤捕獲
when err then
raise_application_error(-20001, '工資太低'); --錯誤處理,-20001/*-20000到20999*/, '未指定項費率'/*2048字節*/
end;