PL/SQL异常处理
系统异常
由数据库管理系统捕获处理 预定义异常:有异常编码,异常名称,异常信息
no_data-found :没有找到数据
too_many_rows :返回多条数据
declare
v_name varchar2(10);
begin
select ename into v_name from test_emp where empno=1234;
dbms_output.put_line(v_name);
exception
when no_data_found then
dbms_output.put_line('no data');
when too_many_rows then
dbms_output.put_line('too many rows');
when others then
dbms_output.put_line('error');
end;
非预定义异常
有编码,有信息,没有异常名称
declare
e_child exception;
pragma exception_init(e_child,-02292);
begin
delete from dept where deptno=10;
dbms_output.put_line('deleted');
exception
when e_child then
dbms_output.put_line('has constraint');
when others then
dbms_output.put_line('others');
end;
自定义异常
由程序员捕获并处理的错误信息
declare
v_id binary_integer := &no;
v_comm test_emp.comm%type;
--定义异常名称
e_null exception;
--将异常名称跟异常编码绑定
pragma exception_init(e_null,-20101);
begin
select comm into v_comm from test_emp where empno=v_id;
dbms_output.put_line(v_comm);
if v_comm is null then
--抛出异常
raise e_null;
else
update test_emp set comm=comm+100 where empno=v_id;
end if;
exception
--捕获异常
when e_null then
dbms_output.put_line('comm is null');
--捕获其他类型的异常
when others then
dbms_output.put_line('others');
end;
--------示例 2--------
declare
v_id binary_integer := &no;
v_comm test_emp.comm%type;
e_null exception;
pragma exception_init(e_null,-20101);
begin
select comm into v_comm from test_emp where empno=v_id;
dbms_output.put_line(v_comm);
if v_comm is null then
raise e_null;
else
update test_emp set comm=comm+100 where empno=v_id;
commit;
end if;
exception
when others then
--打印输出异常编码 sqlcode 和异常信息
sqlerrm dbms_output.put_line(sqlcode||'---'||sqlerrm);
end;
如果在循环中出现异常信息会中断代码块的继续执行,如果需要抛出异常以后继续执行代码块需要使用如下结构:
EXCEPTION
when others then
null;
在 for …LOOP ENDLOOP 循环中捕捉异常,必须用 begin end 包起来,否则会
报错
declare
V_SQL VARCHAR2(255);
errorCode number; --异常编码
errorMsg varchar2(1000); --异常信息
out_return varchar2(1000);
flag varchar2(10);
CURSOR TP IS
SELECT TABLE_NAME,CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'P';
BEGIN
FOR E IN TP LOOP
BEGIN
V_SQL := 'ALTER TABLE ' || E.TABLE_NAME || ' ' || 'DISABLE' ||' '|| 'CONSTRAINT ' || E.CONSTRAINT_NAME;
DBMS_OUTPUT.PUT_LINE(V_SQL);
EXECUTE IMMEDIATE (V_SQL);
---- 异常捕获
EXCEPTION
when others then
errorCode := SQLCODE;
errorMsg := SUBSTR(SQLERRM, 1, 200);
flag := 'false';
out_return := 'flag=' || flag || ',errorCode='||errorCode || ',errorMsg=' || errorMsg;
dbms_output.put_line(out_return);
null;
END;
END LOOP;
end;
更多相关知识,请关注我哦,或者猛戳头像,谢谢!