语法:
declare
……………………;
begin
……………………;
……………………;
exception
when ex1 then
…………;
when ex2 then
…………;
when others then
………………;
end;
1、使用系统预定义异常
begin
declare
v_dname dept.dname%type;
begin
select dname into v_dname from dept where deptno=0;
dbms_output.put_line('部门名称:'||v_dname);
exception
when NO_DATA_FOUND then
dbms_output.put_line('异常:没有该部门');
when others then
dbms_output.put_line('异常:其他未知异常');
end;
end;
2、使用自定义异常
begin
declare
e_ex exception;
begin
update dept set loc='测试SSS' where deptno=0;
if SQL%NOTFOUND then
raise e_ex;
end if;
dbms_output.put_line('没有出现异常');
exception
when e_ex then
dbms_output.put_line('异常:没有该部门');
when others then
dbms_output.put_line('异常:其他未知异常');
end;
end;
3、使用异常处理函数
begin
declare
v_value integer;
begin
v_value:=5/0;
dbms_output.put_line('没有出现异常');
exception
when NO_DATA_FOUND then
dbms_output.put_line('异常:没有该部门');
when others then
dbms_output.put_line('异常:错误号:'||SQLCODE()||' 错误信息:'||SQLERRM());
end;
end;
使用SQLCODE与SQLERRM
begin
declare
v_deptno dept.deptno%type;
begin
v_deptno:=0;
update dept set loc='测试' where deptno=v_deptno;
if SQL%NOTFOUND then
raise_application_error(-20000, '该部门不存在');
end if;
dbms_output.put_line('没有出现异常');
end;
end;
使用raise_application_error抛出异常