今天爱分享给大家带来PLSQL编程-意外【详细讲解】,希望能够帮助到各位。
一、含义
意外是程序运行的过程发生的异常,相当于是Java中的异常
二、语法
declare
--声明变量
begin
--业务逻辑
exception
--处理异常
when 异常1 then
...
when 异常2 then
...
when others then
...处理其它异常
end;
三、分类
系统异常
zero_divide :除数为零异常
value_error :类型转换异常
no_data_found : 没有找到数据
too_many_rows : 查询出多行记录,但是赋值给了%rowtype一行数据变量
自定义异常
declare
--声明变量
异常名称 exception;
begin
--业务逻辑
if 触发条件 then
raise 异常名称; --抛出自定义的异常
exception
--处理异常
when 异常名称 then
dbms_output.put_line('输出了自定义异常');
when others then
dbms_output.put_line('输出了其它的异常');
end;
四、演示
1、内置系统异常
vi number;
vrow emp%rowtype;
begin
--以下四行对应四个异常,测试请依次放开
vi := 8/0;
--vi := 'aaa';
--select * into vrow from emp where empno = 1234567;
--select * into vrow from emp;
exception
when zero_divide then
dbms_output.put_line('发生除数为零异常');
when value_error then
dbms_output.put_line('发生类型转换异常');
when no_data_found then
dbms_output.put_line('没有找到数据异常');
when too_many_rows then
dbms_output.put_line('查询出多行记录,但是赋值给了%rowtype一行数据变量');
when others then
dbms_output.put_line('发生了其它的异常' || sqlerrm);
end;
2、抛出系统异常
--查询指定编号的员工,如果没有找到,则抛出系统异常
declare
--1.声明一个变量 %rowtype
vrow emp%rowtype;
begin
--查询员工信息,保存起来
select * into vrow from emp where empno = 8000;
--判断是否触发异常的条件
if vrow.sal is null then
--抛出系统异常
raise_application_error(-20001,'员工工资为空');
end if;
exception
when others then
dbms_output.put_line('输出了其它的异常' || sqlerrm);
end;
3、抛出自定义异常
--查询指定编号的员工,如果没有找到,则抛出自定义异常
declare
--1.声明一个变量 %rowtype
vrow emp%rowtype;
--2.声明一个自定义的异常
no_emp exception;
begin
--查询员工信息,保存起来
select * into vrow from emp where empno = 8000;
--判断是否触发异常的条件
if vrow.sal is null then
raise no_emp; --抛出自定义的异常
end if;
exception
when no_emp then
dbms_output.put_line('输出了自定义异常');
when others then
dbms_output.put_line('输出了其它的异常' || sqlerrm);
end;
原文链接:http://blog.itblood.com/206.html,转载请注明出处。

![我的乡村日常生活v0.3.3[PC+安卓/2.98G/更新] [神作RPG/AI汉化]](/wp-content/uploads/replace/2025/09/12/49bd83234ecea3de26ef5611279d7dcf.webp)