Oracle筆記 七、PL/SQL 異常處理

來源:互聯網
上載者:User

標籤:

--異常處理
declare
  sNum number := 0;
begin
  sNum := 5 / sNum;  
  dbms_output.put_line(sNum);
exception 
  when others then
    dbms_output.put_line(‘is Error!‘);
end;
 
--自訂異常
declare
       ex_custom_invaild_age exception; --自訂的異常myerr
       age int;
begin
     age := &請輸入年齡;
     if (age < 0) then
        raise ex_custom_invaild_age; --引發自訂異常
     else
        dbms_output.put_line(‘年齡是:‘ || age);     
     end if;
exception 
      when ex_custom_invaild_age then
        dbms_output.put_line(‘非法的年齡‘);
end;
 
--引發應用程式異常
--raise_application_error(異常編號,說明);
declare        
       age int;
begin
     age := &請輸入年齡;
     if (age < 0) then
        raise_application_error(-20500, ‘年齡不能為負數‘);
     else
        dbms_output.put_line(‘年齡是:‘ || age);
     end if;
end;
 
--非預定義異常
declare     
     ex_custom_error exception;
     pragma exception_init(ex_custom_error, -1); --把一個編號和一個自訂異常關聯,
     --相當於把-1編號的異常命名為ex_custom_error,這樣就可以捕獲這種異常
begin       
     insert into dept values(10, ‘aaa‘, ‘bbb‘);
     exception       
       when ex_custom_error then
       dbms_output.put_line(‘部門編號已經存在‘);
end;
 
--異常處理
declare
  vSal emp.sal%type;
begin
  select sal into vSal from emp;
  exception
    when too_many_rows then
      dbms_output.put_line(‘多條資料‘);
    when others then
      dbms_output.put_line(‘Error‘);
end;
 
declare
  vSal emp.sal%type;
begin
  select sal into vSal from emp where empno = 1;
  exception
    when no_data_found then
      dbms_output.put_line(‘沒有資料‘);
    when others then
      dbms_output.put_line(‘Error‘);
end;
 
--異常Tlog
create table errorLog (
       id number primary key,
       errCode number,
       errMsg varchar2(1024),
       errDate date
);
--建立序列,從1開始,每次加1
create sequence seq_errorLog_id start with 1 increment by 1;
 
declare
       vDeptno dept.deptno%type := 10;
       vErrCode number;
       vErrMsg varchar2(1024);
begin
  delete from dept where deptno = vDeptno;
  commit;
  exception
    when others then
      rollback;
      vErrCode := SQLCODE;
      vErrMsg := SQLERRM;
      insert into errorLog values(seq_errorLog_id.nextval, vErrCode, vErrMsg, sysdate);
      commit;
end;
 
select * from errorLog;

Oracle筆記 七、PL/SQL 異常處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.