Loading

存储过程--异常捕获

存储过程异常捕获

创建存储过程

  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;

其他

  • 当异常产生后会直接跳到exception匹配对应的异常名,并执行异常内部的相关代码
  • 异常的分类:内部异常和用户自定义异常
    • 常见的内部异常有如下
      • no_data_found:select into 语句没有符合条件的记录返回
      • too_many_rows:select into 语句符合条件的记录有多条返回

循环时异常处理

需求:循环输出遍历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 ... loopend loop 中间一定要有一个begin...end,然后异常捕捉在其中进行。
  • 捕捉后可进行操作,或者直接不操作,就null;

抛出异常

  • raise 异常名
    • raise no_data_found表示抛出数据没找到异常

参考资料

posted @ 2021-09-06 18:38  ^Mao^  阅读(644)  评论(0编辑  收藏  举报