標籤:
--異常處理
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 異常處理