程序执行过程中出现错误情况被称为在pl/sql异常。 pl/sql支持程序员在程序中使用异常块捕获这样的条件并采取适当的动作应对错误情况。有两种类型的异常:定义的异常、用户定义的异常
异常处理语法
一般异常处理的语法如下。在这里可以列出下来很多,要处理异常。默认的异常将使用when others then处理:
declare
begin
exception
when exception1 then
exception1-handling-statements
when exception2 then
exception2-handling-statements
when exception3 then
exception3-handling-statements
........
when others then
exception3-handling-statements
end;
预定义异常
pl/sql提供许多预先定义的异常,这是在被执行时的任何规则由程序引发。例如,预定义异常no_data_found时引发一个select into语句返回数据行。下表列出了一些重要的预先定义的异常:
操作实例一 除以零的操作异常:
-- created on 2018/4/2 by e.wang
/*
默认的异常将使用when others then处理:
declare
begin
exception
when exception1 then
exception1-handling-statements
when exception2 then
exception2-handling-statements
when exception3 then
exception3-handling-statements
........
when others then
exception3-handling-statements
end;
*/
declare
--定义一个简单的变量
i integer;
begin
--
i:=30;
--当没有任何选择,在当选择一个case语句的子句,并且没有else子句时被引发
case
when i=35 then dbms_output.put_line('it is right!');
--它被引发当一个数试图除以零。
when i/0=0 then dbms_output.put_line('condition is error');
end case;
--异常获取代码块
exception
when case_not_found then
dbms_output.put_line('no case substate!');
--它被引发当一个数试图除以零
when zero_divide then
dbms_output.put_line('zero is not pided!');
end;
操作实例一运行结果截图:
操作实例二 引发异常:
-- created on 2018/4/2 by e.wang
/*
异常是数据库服务器自动在内部数据库错误,但异常可以明确地提出由程序员使用命令raise。
以下是引发异常的简单的语法:
declare
exception_name exception;
begin
if condition then
raise exception_name;
end if;
exception
when exception_name then
statement;
end;
可以在引发oracle的标准异常或任何用户定义的异常使用上述语法。
*/
declare
--定义一个简单的变量
i integer;
begin
--
i:=30;
--它被引发当一个数试图除以零。
if i/0=0 then
raise zero_divide;
end if;
--异常获取代码块
exception
--它被引发当一个数试图除以零
when zero_divide then
dbms_output.put_line('zero is not pided!');
end;