存储过程--异常捕获

时间:2021-09-06 21:51:07   收藏:0   阅读:26

存储过程异常捕获

创建存储过程

  1. 创建存储过程
create or replace procedure test_exception(
  param1 in int, --输入参数
  param2 in int 
) 
is
	-- 全局变量
	val int;
begin
	val :=  param1/param2;
	select val;
end;
  1. 执行存储过程
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;

其他

循环时异常处理

需求:循环输出遍历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;

抛出异常

参考资料

原文:https://www.cnblogs.com/it774274680/p/15235112.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!