create or replace procedure test_exception(
param1 in int, --输入参数
param2 in int
)
is
-- 全局变量
val int;
begin
val := param1/param2;
select val;
end;
call test_exception(10/5)
上面在执行call test_exception(10/0)
会出现报错,导致后续sql无法执行。
解决存储过程中出现异常的情况,让程序更健壮。
Exception
when exception1 then 异常处理1;
when exception2 then 异常处理2;
...
when others then 其他处理;
对除0异常
,其他的异常进行其他逻辑处理
create or replace procedure test_exception(
param1 in int,
param2 in int
)
is
val int;
begin
val := param1/param2;
select val;
Exception
when zero_divide then
select ‘发生除0错误‘;
when others then
...;
end;
如果想针对某种异常不进行处理的话
Exception when others then null;
如果不确定会报什么异常的话,想要获取异常信息。可以在Exception语句块中通过SQLCODE
获取异常代码编号;通过SQLERRM
获取异常的相关信息
Exception when others then
select SQLCODE,SQLERRM;
其他
exception
匹配对应的异常名,并执行异常内部的相关代码需求:循环输出遍历1到3,遇到2抛出数据没找到,然后继续往后循环
create or replace procedure test_exception
is
val int;
begin
for i in 1..3 loop
begin
if i=2 then
raise no_data_found;
end if;
select i;
exception
when others then
select SQLCODE,SQLERRM;
end;
end loop;
end;
for ... loop
到 end loop
中间一定要有一个begin...end
,然后异常捕捉在其中进行。raise 异常名
。
raise no_data_found
表示抛出数据没找到异常原文:https://www.cnblogs.com/it774274680/p/15235112.html