您的位置:首页 > 数据库 > Oracle

Oracle笔记 七、PL/SQL 异常处理

2015-10-12 22:15 579 查看
--异常处理

declare

sNumnumber:=0;

begin

sNum:=5/sNum;

dbms_output.put_line(sNum);

exception

whenothersthen

dbms_output.put_line('isError!');

end;


--自定义异常

declare

ex_custom_invaild_ageexception;--自定义的异常myerr

ageint;

begin

age:=&请输入年龄;

if(age<0)then

raiseex_custom_invaild_age;--引发自定义异常

else

dbms_output.put_line('年龄是:'||age);

endif;

exception

whenex_custom_invaild_agethen

dbms_output.put_line('非法的年龄');

end;


--引发应用程序异常

--raise_application_error(异常编号,说明);

declare

ageint;

begin

age:=&请输入年龄;

if(age<0)then

raise_application_error(-20500,'年龄不能为负数');

else

dbms_output.put_line('年龄是:'||age);

endif;

end;


--非预定义异常

declare

ex_custom_errorexception;

pragmaexception_init(ex_custom_error,-1);--把一个编号和一个自定义异常关联,

--相当于把-1编号的异常命名为ex_custom_error,这样就可以捕获这种异常

begin

insertintodeptvalues(10,'aaa','bbb');

exception

whenex_custom_errorthen

dbms_output.put_line('部门编号已经存在');

end;


--异常处理

declare

vSalemp.sal%type;

begin

selectsalintovSalfromemp;

exception

whentoo_many_rowsthen

dbms_output.put_line('多条数据');

whenothersthen

dbms_output.put_line('Error');

end;


declare

vSalemp.sal%type;

begin

selectsalintovSalfromempwhereempno=1;

exception

whenno_data_foundthen

dbms_output.put_line('没有数据');

whenothersthen

dbms_output.put_line('Error');

end;


--异常日志处理

createtableerrorLog(

idnumberprimarykey,

errCodenumber,

errMsgvarchar2(1024),

errDatedate

);

--创建序列,从1开始,每次加1

createsequenceseq_errorLog_idstartwith1incrementby1;


declare

vDeptnodept.deptno%type:=10;

vErrCodenumber;

vErrMsgvarchar2(1024);

begin

deletefromdeptwheredeptno=vDeptno;

commit;

exception

whenothersthen

rollback;

vErrCode:=SQLCODE;

vErrMsg:=SQLERRM;

insertintoerrorLogvalues(seq_errorLog_id.nextval,vErrCode,vErrMsg,sysdate);

commit;

end;


select*fromerrorLog;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: