1.概述
(1)异常:指pl/sql的运行时错误。
(2)任何pl/sql块都可以有一个异常处理块,其中可以包含一个或多个异常处理器,格式:
exception
when ex1 then 语句1
when ex2 or ex3 then 语句2
when others then 语句3
(3)异常类型:内置异常;自定义异常。
a:内置异常
它是以ora-n的错误;如果发生这类错误,会隐式的抛出。常见:no_data_found|too_many_rows|zero_pide|value_error等。
b:自定义异常
可用 ex_name exception进行定义;必须显示抛出。
2.异常声明
(1)内置的异常,无需声明,可直接使用;自定义异常需要单独声明。
(2)声明语法:
ex_name exception
(3)关联异常与错误代码
pragma exception_init(ex_name,error_code)
3.异常抛出
(1)raise
raise:将当前捕获到的异常原样抛出。
raise ex_name:将抛出名为ex_name的异常。
(2)raise_application_error(用于未命名的自定义异常,将错误编号和错误文本关联起来)
作用:用于未命名的自定义异常,将错误编号和错误文本关联起来。
格式:raise_application_error(error_code,message);或 raise_application_error(erro_code,message,keep_errors);
error_code:错误编码,范围在-20999到-20000之间。
message:错误文本,最多包含2048个字符。
keep_errors:它是boolean参数,为true时,新错误被添加到已经抛出的错误列表中;为false时,新错误会替换已经抛出的错误栈。
4.异常处理
预定义异常
定义部分:异常名称 exception;
pragma exception_init(错误名,- 错误代码); 将错误名称、错误代码关联起来。
异常处理:
when 错误名 then
语句块; 自定义异常
定义部分:异常名称 exception;
抛出异常:raise 异常名称;
异常处理:
when 异常名称 then
语句块;
5.自定义异常示例
自定义异常示例一:
declare
--1.声明异常
e_invalid_id exception;
v_num number:=1;
begin
if v_num =1 then
raise e_invalid_id;--2.抛出异常
end if;
exception
when e_invalid_id then --3.发生异常时处理
dbms_output.put_line('my first exception!');
end;
示例二:
--自定义异常
declare
xiao_dog exception;--声明部分
n_num number(2):=10;
begin
if n_num=10 then raise xiao_dog; --通过raise 异常名来抛出异常
end if;
exception
when xiao_dog then --发生异常时做什么
dbms_output.put_line(' xiao_dog exception ......');
end;
raise_application_error示例:
declare
v_num number:=1;
begin
if v_num =1 then
raise_application_error(-20001,'错误文本区域,这是第二个错误。');
end if;
exception
when others then
raise;
end;
exception_init示例:
declare
v_zip zipcode.zip%type:=&sv_zip;
e_child_exists exception;
pragma exception_init(e_child_exists,-2292);
begin
delete from zipcode where zip=v_zip;
dbms_output.put_line('zip'||v_zip||' has been deleted');
commit;
exception
when e_child_exists then
dbms_output.put_line('delete students for this zipcode first');
end;
6.异常传播
内部块的异常如果有没有异常处理部分,直接跳转到外部块中的异常处理部分;如果内部块中有异常处理部分,先执行内部异常处理,再跳到外部块,继续执行外部块里的内容。
声明处发生异常会直接跳转到此块所属块的异常处理部分;如果没有就直接转到主机环境。
7.异常内置函数
sqlcode:返回错误编号
sqlerrm:返回错误信息,错误信息最大长度为512字节。
示例:
declare
v_student_id number:=101;
v_name varchar2(30);
begin
select rtrim(first_name)||' '||rtrim(last_name) into v_name from student where student_id=v_student_id;
exception
when others then
dbms_output.put_line('错误代码:'||sqlcode);
dbms_output.put_line('错误文本:'||substr(sqlerrm,1,200));
end;