oracle異常處理

語句執行過程當中,因爲各類緣由使得語句不能正常執行,可能會形成更大錯誤或整個系統的崩潰,因此PS/SQL提供了異常(exception)着一處理的方法來防止此類狀況的發生。在代碼運行的過程當中不管什麼時候發生錯誤,PL/SQL都能控制程序自動地轉向執行異常部分。函數

1.預約義異常spa

預約義異常是因爲系統產生的。例如出現0除,PL/SQL就會產生一個預約義的ZERO_DIVIDE異常。3d

--ZERO_DIVIDE異常。使用系統預約義的異常處理,使用該處理後,程序運行時系統就不會提示出現錯誤。
 
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('除數不能爲0');
  end;
輸出結果:DIVIDE ZERO

 

2.PL/SQL中常見的異常:code

 

 

3.轉換的錯誤處理blog

declare
  v_number1 number(3);
  v_char  char(5):='123c';
  begin
     v_number1:=to_number(v_char);  //將字符轉換成數字
     DBMS_OUTPUT.PUT_LINE('轉換成功');
     EXCEPTION
        when value_error then
          DBMS_OUTPUT.PUT_LINE('轉換沒成功');
  end;

 

4.聯合的錯誤處理io

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('沒有數據');
        when  too_many_rows then
           dbms_output.put_line('數據太多');
        when  ZERO_DIVIDE then
           dbms_output.put_line('列出錯列');
      
  end;

 

5.用戶定義異常class

--用戶能夠經過自定義異常來處理髮生的錯誤,語法格式爲:
exception
   when 異常名 then
        語句塊 1;
    when  then
        語句塊2;
    [when others then
         語句塊3;]
end;

 注意:每一個異常處理部分都是由when子句和相應的執行語句組成select

 

6.自定義異常exception

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;

注意:同一個異常不容許多個when子句來處理,一個異常對應一個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('出錯了');
  end;

對於一個異常有兩個處理方式,分別位於不一樣的when子句,所以系統會認爲是不合法的。可使用others來處理那些不能由其餘when子句處理的異常,others異常處理老是位於exception語句的最後。

其實,others異常處理能夠藉助兩個函數來講明捕捉到的異常的類型,這兩個函數是PL/SQL和SQLERRM,其中SQLLOCODE是用來講明當前錯誤的代碼,若是是用戶自定義異常。則返回1.SQLERRM返回的是當前錯誤的信息。

 

8.空操做和空值

declare
  n number(3):=-1;
  begin
     if n<0 then
         null;
     else
        DBMS_OUTPUT.PUT_LINE('正常');
     end if;
  end;
相關文章
相關標籤/搜索