ORACLE的PLSQL编程,异常处理主要分为3大块
AORACLE系统预定义异常 ,比如NO_DATA_FOUND;
B非预定义异常 ,用PRAGMA定义
C自定义异常
下面是主要的测试脚本
--除数为零的异常处理(预定义异常)
set serveroutput on;
declare
v_dividend number:=50;
v_divisor number:=0;
v_quotient number;
begin
v_quotient:=v_dividend/v_divisor;
exception
when ZERO_DIVIDE THEN
dbms_output.put_line('除数为零');
end;
/
--no_data_foud异常(预定义异常)
select * from students;
declare
v_id students.student_id%type;
v_sname students.name%type;
begin
v_id:=&student_id;
select name into v_sname from students where student_id=v_id;
dbms_output.put_line('学生姓名'||v_sname);
exception
when no_data_found then
dbms_output.put_line('输入的学号不存在');
end;
--too_many_rows 异常(预定义异常)
declare
v_SPECIALTY students.SPECIALTY%type;
v_sname students.name%type;
begin
v_SPECIALTY:='&specialty';
select name into v_sname from students where SPECIALTY=v_SPECIALTY;
dbms_output.put_line('学生姓名'||v_sname);
exception
when too_many_rows then
dbms_output.put_line('返回的学生记录多于一行');
end;
--考虑两种系统预定义异常 too_many_rows 和no_data_found异常(预定义异常)
declare
v_SPECIALTY students.SPECIALTY%type;
v_sname students.name%type;
begin
v_SPECIALTY:='&specialty'; --这里的加引号和上面的不加引号有什么不一样?
select name into v_sname from students where SPECIALTY=v_SPECIALTY;
dbms_output.put_line('学生姓名'||v_sname);
exception
when too_many_rows then
dbms_output.put_line('返回的学生记录多于一行');
when no_data_found then
dbms_output.put_line('没有记录');
end;
--非预定义异常 e_deptid EXCEPTION;(删除有主外键约束的表的异常处理)
-- pragma EXCEPTION_INIT(e_deptid ,-2292);
select * from departments;
set serveroutput on;
declare
e_deptid EXCEPTION;
pragma EXCEPTION_INIT(e_deptid ,-2292);
begin
delete from departments where department_id=101;
exception
when e_deptid then
dbms_output.put_line('在教师表中存在子记录'); --参照完整性异常,看似不会产生异常,但是假如于其他表有主外键关联则会出异常
end;
--插入有主外键约束的表的处理
select * from teachers;
set serveroutput on;
declare
e_deptid EXCEPTION;
pragma EXCEPTION_INIT(e_deptid ,-2292);
begin
insert into teachers values (11101,'王彤','教授','01-9月-1990',1000,3000,999);
exception
when e_deptid then
dbms_output.put_line('插入记录的部门号在父表中不存在'); --参照完整性异常,看似不会产生异常,但是假如于其他表有主外键关联则会出异常
end;
---插入的记录已经存在异常
select * from students;
set serveroutput on;
declare
e_studentid EXCEPTION;
pragma EXCEPTION_INIT(e_studentid ,-0001);
begin
insert into students values (10205,null,'王三','男','26-12月-1989','自动化');
exception
when e_studentid then
dbms_output.put_line('插入记录已经存在---'||SQLCODE||'错误描述---'||SQLERRM); --参照完整性异常,看似不会产生异常,但是假如于其他表有主外键关联则会出异常
end;
--自定义异常
declare
e_wage EXCEPTION;
v_wage teachers.wage%type;
begin
v_wage:=&wage;
insert into teachers values (10111,'王彤','教授','01-9月-1990',1000,v_wage,101);
if v_wage <0 then
raise e_wage;
end if;
exception
when e_wage then
dbms_output.put_line('教师工资不能为负');
rollback;
when others then
dbms_output.put_line('未知异常');
end;
/