語句執(zhí)行過程中,由于各種原因使得語句不能正常執(zhí)行,可能會(huì)造成更大錯(cuò)誤或整個(gè)系統(tǒng)的崩潰,所以PS/SQL提供了異常(exception)著一處理的方法來防止此類情況的發(fā)生。在代碼運(yùn)行的過程中無論何時(shí)發(fā)生錯(cuò)誤,PL/SQL都能控制程序自動(dòng)地轉(zhuǎn)向執(zhí)行異常部分。 1.預(yù)定義異常 預(yù)定義異常是由于系統(tǒng)產(chǎn)生的。例如出現(xiàn)0除,PL/SQL就會(huì)產(chǎn)生一個(gè)預(yù)定義的ZERO_DIVIDE異常。 --ZERO_DIVIDE異常。使用系統(tǒng)預(yù)定義的異常處理,使用該處理后,程序運(yùn)行時(shí)系統(tǒng)就不會(huì)提示出現(xiàn)錯(cuò)誤。 declare v_number1 number(3):=10; v_number2 number(3):=0; v_number3 number(3); begin v_number3:=v_number1/v_number2; DBMS_OUTPUT.PUT_LINE(v_number3); EXCEPTION when ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE('除數(shù)不能為0'); end;
2.PL/SQL中常見的異常:
3.轉(zhuǎn)換的錯(cuò)誤處理 declare v_number1 number(3); v_char char(5):='123c'; begin v_number1:=to_number(v_char); //將字符轉(zhuǎn)換成數(shù)字 DBMS_OUTPUT.PUT_LINE('轉(zhuǎn)換成功'); EXCEPTION when value_error then DBMS_OUTPUT.PUT_LINE('轉(zhuǎn)換沒成功'); end;
4.聯(lián)合的錯(cuò)誤處理 declare v_name school_students.stu_name%type; begin select stu_name into v_name from school_students where stu_id='2016322180021'; dbms_output.put_line(v_name); EXCEPTION when no_data_found then dbms_output.put_line('沒有數(shù)據(jù)'); when too_many_rows then dbms_output.put_line('數(shù)據(jù)太多'); when ZERO_DIVIDE then dbms_output.put_line('列出錯(cuò)列'); end;
5.用戶定義異常 --用戶可以通過自定義異常來處理發(fā)生的錯(cuò)誤,語法格式為: exception when 異常名 then 語句塊 1; when then 語句塊2; [when others then 語句塊3;] end; 注意:每個(gè)異常處理部分都是由when子句和相應(yīng)的執(zhí)行語句組成
6.自定義異常 declare e_name exception; v_num number(8); begin select count(*) into v_num from school_students; if v_num>10 then RAISE e_name; end if ; exception when e_name then dbms_output.put_line('最大值不能超過10'); end; 注意:同一個(gè)異常不允許多個(gè)when子句來處理,一個(gè)異常對(duì)應(yīng)一個(gè)when子句。
7.使用others異常 declare v_name school_students.stu_name%type; begin select stu_name into v_name from school_students where stu_id='2016322180021'; dbms_output.put_line(v_name); EXCEPTION when OTHERS then dbms_output.put_line('出錯(cuò)了'); end; 對(duì)于一個(gè)異常有兩個(gè)處理方式,分別位于不同的when子句,因此系統(tǒng)會(huì)認(rèn)為是不合法的??梢允褂胦thers來處理那些不能由其他when子句處理的異常,others異常處理總是位于exception語句的最后。 其實(shí),others異常處理可以借助兩個(gè)函數(shù)來說明捕捉到的異常的類型,這兩個(gè)函數(shù)是PL/SQL和SQLERRM,其中SQLLOCODE是用來說明當(dāng)前錯(cuò)誤的代碼,如果是用戶自定義異常。則返回1.SQLERRM返回的是當(dāng)前錯(cuò)誤的信息。
8.空操作和空值 declare n number(3):=-1; begin if n<0 then null; else DBMS_OUTPUT.PUT_LINE('正常'); end if; end;
|
|