首页 > 代码库 > 【PL/SQL练习】自定义异常
【PL/SQL练习】自定义异常
由用户自己定义
1、定义异常名称,类型exception
2、举出异常(raise excepttion)
3、捕获异常
SQL> declare
2 e_user_err exception;
3 v_deptno dept.deptno%type := &no;
4 begin
5 update dept set loc=‘HongKong‘ where deptno=v_deptno;
6
7 if sql%notfound then
8 raise e_user_err;
9 end if;
10 commit;
11 exception
12 when e_user_err then
13 dbms_output.put_line(‘This department ‘||v_deptno|| ‘ is not in dept table ,please input correct number !‘);
14 end;
非预定义异常,通过oracle ORA-XXXX错误代码,建立异常捕获!
-------违背了参考性约束
declare
e_emp_remain exception;
pragma exception_init( e_emp_remain ,-2292);
v_deptno dept.deptno%type :=&no;
begin
delete from dept where deptno=v_deptno;
commit;
exception
when e_emp_remain then
dbms_output.put_line (‘Don‘‘t remove this ‘||v_deptno||‘ department !‘||‘ , This record is in emp !‘);
when others then
dbms_output.put_line (‘Others error !‘);
end;
SQL> declare
2 e_emp_remain exception;
3 pragma exception_init( e_emp_remain ,-2291);
4
5 v_empno emp.empno%type :=&n;
6 v_deptno emp.deptno%type :=&nn;
7
8 begin
9 update emp set deptno=v_deptno where empno=v_empno;
10 commit;
11 exception
12 when e_emp_remain then
13 dbms_output.put_line (‘Department is not exists !‘);
14 when others then
15 dbms_output.put_line (‘Others error !‘);
16 end;
获取others中错误代码和错误信息:
sqlcode: oracle 错误代码 sqlerrm: oracle 错误信息
SQL> declare
2 v_code errors.code%type;
3 v_msg errors.msg%type;
4 v_sal emp.sal%type;
5
6 begin
7
8 select sal into v_sal from emp where deptno=&no;
9
10 exception
11 when no_data_found then
12 dbms_output.put_line(‘No this department ID‘);
13 when others then
14 dbms_output.put_line(‘Others error ‘);
15 v_code := sqlcode;
16 v_msg := sqlerrm;
17 dbms_output.put_line(v_msg);
18
19 insert into errors values(v_code,v_msg);
20 commit;
21 end;
通过捕获的代码建立非预定义异常:
SQL> declare
2 e_emp_err exception;
3 pragma exception_init( e_emp_err ,-1422);
4
5 v_sal emp.sal%type;
6
7 begin
8 select sal into v_sal from emp where deptno=&no;
9 commit;
10 exception
11 when e_emp_err then
12 dbms_output.put_line (‘ Return rows more than one row !‘);
13 when others then
14 dbms_output.put_line (‘Others error !‘);
15 end;
【PL/SQL练习】自定义异常
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。