异常处理是Oracle中必不可少的部分。
我们常见的异常no_data_found
-
declare
-
inumber;
-
begin
-
select1 onto ifromdualwhere1=2;
-
exception
-
when not_data_found
-
then
-
dbms.output.put_line('not found data')
-
end;
还有when too_many_rows
-
declare
-
nnumber;
-
begin
-
selectidinton
-
from
-
(
-
select1 idfromdual
-
union
-
select2 idfromdual
-
);
-
exception when too_many_rowsthen
-
dbms_output.put_line('too many rows found for n');
-
end;
还有很多我们无法确认的异常处理,这种情况我们可以使用others代替其他所有的异常。
-
EXCEPTION
-
when others then
-
rollback;
-
dbms_output.put_line('code:'||sqlcode);
-
dbms_output.put_line('errm:'||sqlerrm);
-
raise;
when others then和raise;异常分很多种类,如NO_FOUND。others处本应该写异常名称,如果不想把异常分得那麼细,可以笼统一点用others来捕获,即所有异常均用others来捕获。when others then表示是其它异常。
raise表示抛出异常。我们还可以自己定义exception哦!为什么要自己定义呢?即使人为制造exception,中断程序或者跳出某个程序段。
-
DECLARE
-
exception1 EXCEPTION;
-
BEGIN
-
IF1!=1THEN
-
Dbms_Output.put_line('Normal!');
-
ELSE
-
RAISE exception1;
-
ENDIF;
-
EXCEPTION
-
WHEN exception1THEN
-
Dbms_Output.put_line('EXCEPTION!');
-
WHEN OTHERSTHEN
-
Dbms_Output.put_line('OTHERS EXCEPTION!');
-
END;
输出结果是:EXCEPTION!
因为我人为raise了一个exception,所以程序直接跳到了when exception1 then里面去了。
注意:exception一定有一个begin和end。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30260000/viewspace-1826913/
,如需转载,请注明出处,否则将追究法律责任。