PL/SQL异常
PL/SQL有两种类型的异常:
- 内置异常
- 用户定义异常
内置异常
内置异常是隐式抛出的,当发生特定错误时,与该错误相关的内置异常就会抛出
declare
dept_id varchar2(10) := &d_ip;
dept_name varchar2(20);
begin
select name into dept_name from dept where id = dept_id;
dbms_output.put_line('部门名称' || dept_name);
exception
when no_data_found then
dbms_output.put_line('没有这个部门ID');
end;
用户定义异常
用户定义异常:定义自己的异常及如何重新抛出异常,用户定义异常必须显式抛出。注意RAISE语句应该与IF语句一起使用。
declare
dept_id varchar2(10) := &d_ip;
dept_name varchar2(20);
e_invalid_id exception; --声明异常
begin
--用户定义异常必须显式抛出,指明什么条件下抛出异常
if dept_id < 0 then
raise e_invalid_id;
else
select name into dept_name from dept where id = dept_id;
dbms_output.put_line('部门名称' || dept_name);
end if;
exception
when no_data_found then
dbms_output.put_line('没有这个部门ID');
--异常处理部分与内置异常格式相同
when e_invalid_id then
dbms_output.put_line('这是无效的部门ID');
end;
RAISE_APPLICATION_ERROR
RAISE_APPLICATION_ERROR是oracle提供的一种特殊的内置过程,适用于未命名的用户定义异常,它负责把错误编号和错误文本关联起来。
语法 :
RAISE_APPLICATION_ERROR(error_number,error_message);
或者
RAISE_APPLICATION_ERROR(error_number,error_message,keep_errors);
参数说明:
error_number是与特定错误消息相关联的错误编号,这个编号的范围在-20999和-20000之间
error_message是错误文本,最多包含2048个字符
keep_errors是可选参数,如果keep_errors被设置为TRUE,新错误会被添加到已经抛出的错误列表中,这种错误列表被称为错误栈。如果是FALSE,新错误会替换已经抛出的错误栈,keep_errors参数默认是FALSE。
declare
dept_id varchar2(10) := &d_ip;
dept_name varchar2(20);
--e_invalid_id exception; --声明异常
begin
if dept_id < 0 then
raise_application_error (-20000,'这是无效的部门ID');
else
select name into dept_name from dept where id = dept_id;
dbms_output.put_line('部门名称' || dept_name);
end if;
end;
SQLCODE和SQLERRM
oracle提供两个内置函数——SQLCODE和SQLERRM,用于实现others异常处理程序,sqlcode函数会返回oracle错误编号,sqlerrm函数会返回错误消息,sqlerrm函数所返回消息的最大长度是512字节 。
declare
dept_id varchar2(10) := &d_ip;
dept_name varchar2(20);
begin
select name into dept_name from dept where id = dept_id;
dbms_output.put_line('部门名称' || dept_name);
exception
when no_data_found then
dbms_output.put_line(SQLCODE||','||SQLERRM);
end;