一、应用背景:
PL/SQL是SQL的语言的扩展,是SQL和过程语言整合而成一种语言。在PL/SQL中可以完美的使用SQL语句。
但是有时SQL在执行时会产生异常而导致PL/SQL程序终止,为了保证在SQL产生异常时,PL/SQL仍能正常工作,
便产生了异常捕获机制。
二、异常捕获:
1、异常:在PL/SQL执行过程中产生的错误或警告。可以使得的PL/SQL执行终止。
2、作用:捕获异常,使得PL/SQL在程序异常时,也可以正常执行直到结束。
3、位置:异常捕获在exception模块中定义。当在pl/sql中捕获到异常时,执行相应的异常处理代码。
三、PL/SQL中EXCEPTION的使用:
语法:
exception
when excepton_type then
...
end;
exception_type:
no_data_found ----无数据找到异常
too_many_rows ----太多行异常
others ----其它异常
//更多异常请参考ORACLE官方文档的异常介绍。
四、实例应用
1、no_data_found异常使用:
--set serverout on; 打开服务器输出。
declare
v_name varchar2(20);
begin
select sname into v_name from s where sno=200; --当SELECT执行结果无数据时,就会抛出异常。引起需要捕获该异常。
dbms_output.put_line('The name is :' ||v_name);
exception
when no_data_found then
dbms_output.put_line('Error : no data found'); --当捕获到no_data_found异常时,打印no data found;
end;
执行结果:
Error : no data found
PL/SQL procedure successfully completed.
2、too_many_rows异常使用:
--set serverout on; 打开服务器输出。
declare
v_name varchar2(20);
begin
select sname into v_name from s where sno > 2; --当SELECT执行结果中的数据多于一行时,就会抛出异常,需要捕获该异常。
dbms_output.put_line('The name is :' ||v_name);
exception
when too_many_rows then
dbms_output.put_line('Error : too many rows founded'); --当捕获到too_many_rows异常时,打印too many rows founded;
end;
执行结果:
Error : too many rows founded
PL/SQL procedure successfully completed.
3、others异常使用:
--set serverout on; 打开服务器输出。
declare
x number := 50;
a number :=0;
y number;
begin
y := ( 5 * x - 100 )/a;
dbms_output.put_line('The value of Y is : '||y);
exception
when others then --遇到任何异常,都执行then后面的命令
dbms_output.put_line('错误:除数为0');
end;
执行结果:
错误:除数为0
PL/SQL procedure successfully completed.
阅读(537) | 评论(0) | 转发(0) |