例外的概念和系統(tǒng)例外

例外

  • 例外是程序設(shè)計(jì)語(yǔ)言提供的一種功能,用來(lái)增強(qiáng)程序的健壯性和容錯(cuò)性。

ORACLE 中的例外

  • 系統(tǒng)例外

  • 自定義例外

系統(tǒng)例外

  • No_data_found (沒(méi)有找到數(shù)據(jù))
  • Too_many_rows (select..into語(yǔ)句匹配多個(gè)行)
  • Zero_Divide (被零除)
  • Value_error (算術(shù)或轉(zhuǎn)換錯(cuò)誤)
  • Timeout_on_resource (在等待資源時(shí)發(fā)生超時(shí))

No_data_found 案例

--系統(tǒng)例外:no_data_found
SET SERVEROUTPUT ON

DECLARE
 pe_first_name EMPLOYEES.FIRST_NAME%TYPE;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
BEGIN
 --查詢(xún)員工號(hào)是1234的員工姓名
 select first_name,last_name into pe_first_name,pe_last_name from EMPLOYEES where EMPLOYEE_ID=1234;

exception
 when no_data_found then DBMS_OUTPUT.PUT_LINE('沒(méi)有找到該員工');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

Too_many_rows 案例

--系統(tǒng)例外:too_many_rows
SET SERVEROUTPUT ON

DECLARE
 --定義變量
 pe_first_name EMPLOYEES.FIRST_NAME%TYPE;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
BEGIN
 select first_name,last_name into pe_first_name,pe_last_name from EMPLOYEES where DEPARTMENT_ID=60;

exception
 when too_many_rows then DBMS_OUTPUT.PUT_LINE('selectinto 匹配了多行');
 
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/

Zero_Divide 案例

--系統(tǒng)例外:被0除 zero_divide
SET SERVEROUTPUT ON

DECLARE
 --定義變量
 pnum number;
 
BEGIN
 pnum := 1/0;
exception
 when zero_divide then DBMS_OUTPUT.PUT_LINE('1:0不能做除數(shù)');
                       DBMS_OUTPUT.PUT_LINE('2:0不能做除數(shù)');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

value_error 案例

--系統(tǒng)例外:value_error
SET SERVEROUTPUT ON

DECLARE
 --定義變量
 pnum number;
 
BEGIN
 pnum := 'abc';
exception
 when value_error then DBMS_OUTPUT.PUT_LINE('算術(shù)或者轉(zhuǎn)換錯(cuò)誤');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 

自定義例外

  • 定義變量,類(lèi)型是exception
  • 使用raise拋出自定義例外
--自定義例外:查詢(xún)50號(hào)部門(mén)的員工的姓名
SET SERVEROUTPUT ON

DECLARE
 --定義光標(biāo),代表50號(hào)部門(mén)的員工姓名
 cursor cemp is select first_name,last_name from EMPLOYEES where DEPARTMENT_ID = 300;
 
 pe_first_name EMPLOYEES.first_name%type;
 pe_last_name EMPLOYEES.LAST_NAME%TYPE;
 
 --自定義例外
 no_emp_found EXCEPTION;
BEGIN
 --打開(kāi)光標(biāo)
 open cemp;
 
 --直接取一個(gè)員工的姓名
 FETCH cemp into pe_first_name,pe_last_name;
 
 if cemp%notfound then
    --拋出例外
    raise no_emp_found;
 end if;
  
 --關(guān)閉光標(biāo)
 --oracle會(huì)自動(dòng)啟動(dòng)pmon(process monitor) 關(guān)閉光標(biāo)
 close cemp;
exception
 when no_emp_found then DBMS_OUTPUT.PUT_LINE('沒(méi)有找到員工');
 when others then DBMS_OUTPUT.PUT_LINE('其他例外');
end;
/
 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容