异常处理 exception
用来处理正常执行过程中无法预料的事情,程序块的异常处理预定义的错误和自定义的错误
,plsql出现错误没有抛出终止程序运行
分类:
1.预定义错误:predifine
oracle自带24个,系统自动引发
语法:
异常放在程序最后end之前
declare
beginexception
when
first_exception then<code to handle first exception >
例子:
返回多行
declare
v_ename varchar2(30);
begin
select ename into v_ename from emp;
exception --捕获异常,如果没有异常不会进入异常处理
when first_exception --进入对应的异常名称
异常两个重要变量,
1.--sqlcode 错误编码
2.--sqlerrm 错误信息
dbms_output.put_line('错误编码'||sqlcode);
dbms_output.put_line('错误信息 '||sqlerrm);
then<code to handle first exception >
end;
--捕获所有异常
exception
when others then --异常处理
--把上述两个异常合成一个程序
declare
begin
select ename into v_ename from emp;
select 1/0 into v_1 number(4);
exception
when others then
2.非预定义错误
定义一个异常名字
declare
异常名字 exception;
pragma exception_init(异常名字,编码);
begin
语句
exception
when 异常名
db=======
end;
3.用户自定义
raise
if sql%notfound then
rasie 名字
end if;
exception
when 名字
db====
---用户自定义异常
RAISE_APPLICATION_ERROR(-20992, '无效的部门代码');
declare
v_sal emp.sal%type;
v_sal_error exception;
begin
select sal into v_sal from emp where empno = &empno;
if (v_sal < 3000) then
--1、抛出异常
raise v_sal_error; --抛出了异常名就一定要有处理,否则会报错
else
dbms_output.put_line(v_sal);
end if;
exception
when v_sal_error then
dbms_output.put_line('薪资少于3000');
when others then --其他任意异常
dbms_output.put_line('系统异常');
end;