异常

异常和文件
1.异常:在程序运行过程中出现的错误叫异常,包括程序,软件,硬件,网络等
系统异常和自定义异常
(1)no_data_found:未找到数据
zero_divide:除数不能为零
to_many_rows:返回结果超出一行
(2)自定义异常
异常变量的定义:
变量名 exception;

异常的处理方式:抛出异常,捕获异常
抛出异常的方式:
raise 异常变量;
dbms_standard.raise_application_error(异常编码,‘异常信息’)
declare
–声名一个异常变量(自定义一个异常)
exc exception;
begin
raise exc;
end;

begin
dbms_standard.raise_application_error(-20010,‘我的异常’);
end;

捕获异常:
declare
–声名部分
begin
–代码块部分
exception
异常处理部分
when 异常名称 then
处理代码;
when 异常名称 then
处理代码;

 where others then
   处理代码

end;

begin
dbms_output.put_line(1/0);
exception
when zero_divide then
dbms_output.put_line(‘除数不能为0’);
end;
others:可以捕获到所有的异常
declare
–声名一个变量
v varchar2(30);
begin
select ename into v from emp;
exception
when others then
dbms_output.put_line(‘出现了异常’);
end;

–能过异常处理,让出现错误的代码回滚,并且可以记录错误信息

系统异常变量:
sqlcode:获取异常的编码,no_data_found:异常编码是100 不是ora-01403
sqlerrm:获取异常信息

declare
v varchar2(30);
begin
select ename into v from emp where empno=7369;
exception
when no_data_found then
dbms_output.put_line(sqlcode);
dbms_output.put_line(sqlerrm);
dbms_output.put_line(‘不管理发不发生异常都要执行的代码’); --只有在发生异常时才会执行
end;

注意:exception和end之间的代码都是异常处理代码
declare
v varchar2(30);
begin
select ename into v from emp where empno=7369;
exception
when no_data_found then
dbms_output.put_line(sqlcode);
dbms_output.put_line(sqlerrm);
dbms_output.put_line(‘不管理发不发生异常都要执行的代码’); --只有在发生异常时才会执行
end;
declare
v varchar2(30);
begin
begin
select ename into v from emp where empno=7369 and 1=0;
exception
when no_data_found then
dbms_output.put_line(sqlcode);
dbms_output.put_line(sqlerrm);
end;
dbms_output.put_line(‘不管理发不发生异常都要执行的代码’);
end;

(2)异常绑定
将一个异常绑定到自定义异常变量上(绑定之后,可以能过自定义异常变量来捕获该异常)
绑定异常的语法:
declare
异常变量 exception;
pragma exception_init(异常变量,异常编码);
begin

end;

declare
–自定义一个异常变量
exc exception;
–将主键冲突异常和自定义异常exc绑定
pragma exception_init(exc,-00001);
begin
insert into dept values(10,‘dept’,‘loc’);

commit; --事务提交
exception
when exc then
rollback; --事务回滚
dbms_output.put_line(sqlcode);–打印异常编码
dbms_output.put_line(sqlerrm);–打印异常信息
end;

dbms_standard.raise_application_error(自定义异常编码,异常信息);
业务异常或应用异常

自定义异常编码:范围:-20000~-20999

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值