PL/SQL——例外

例外

例外是程序设计语言提供的一种功能,用来增强程序的健壮性和容错性

在PL/SQL程序中必须捕获所有意外,否则将抛给数据库处理,将造成数据库运行出错。

 

系统例外之——no_data_found(没有找到数据)

set serveroutput on

declare

       pename emp.ename%type;

begin

       --查询员工号1234(数据库中并不存在该员工号)的员工姓名

       select ename into pename from emp where empno=1234;

      

exception

when no_data_found then dbms_output.put_line(‘没有找到该员工’);

when others then dbms_output.put_line(‘其他例外’);

end;

/

 

 

系统例外之——too_many_rows(select…into语句匹配到多个行)

set serveroutput on

declare

       --定义变量

       pename emp.ename%type;

begin

       --查询所有10号部门的员工姓名

       select ename into pename from emp where deptno=10;

      

       exception

       when too_many_rows then dbms_output.put_line(‘select into 匹配了多行’);

       when others then dbms_output.put_line(‘其他例外’);

end;

/

 

 

系统例外之——zero_divide(被零除)

set serveroutput on

declare

       --定义一个基本变量

       pnum number;

begin

       pnum:=10;

exception

       when zero_divide then dbms_output.out_line(‘1:0不可以做除数’);

       --then相当于大括号,后面可以接多条语句

                                          dbms_output.out_line(‘2:0不可以做除数’);

       when others then dbms_output.put_line(‘其他例外’);

end;

/

 

 

系统例外之——value_error(算术或转换错误)

set serveroutput on

declare

       --定义一个number变量

       pnum number;

begin

       pnum:=’abc’;

      

       exception

       when value_error then dbms_output.put_line(‘算术或者转换错误’);

       when others then dbms_output.put_line(‘其他例外’);

end;

/

 

 

系统例外之——timeout_on_resource(在等待资源时发生超时)

自定义例外

定义变量,类型是exception

使用raise抛出自定义例外

 

set serveroutput on

 

declare

       --定义光标,代表50号部门的员工姓名

       cursor cemp is select ename from emp where deptno=50;

       pename emp.ename%type;

       --自定义例外

       no_emp_found exception;

begin

       --打开光标

       open cemp;

       --直接取一个员工的姓名

       fetch cemp into pename;

       --关闭光标

       --oracle自动启动pmom(process monitor)当程序被异常退出,

--该进程会自动释放掉关闭掉系统中的资源

       close cemp;

       exection

       when no_emp_found then dbms_output.put_line(‘没有找到员工’);

       when others then dbms_output.put_line(‘其他例外’);

end;

/

猜你喜欢

转载自blog.csdn.net/qq_37117521/article/details/81712997