PL \ SQL函数之间的异常处理

时间:2015-09-30 15:02:01

标签: oracle exception plsql exception-handling

我有第一个这样的程序

procedure p1(a in varchar2)
is 
begin 
  -- call second procedure
  p2(a);
  -- other things
end;

我的第二个程序可能有例外:

procedure p2(a in varchar2)
is
  lv varchar2(20);
begin
   select '1' into lv from dual;

   if lv = '2' then
     raise general_exception;
   end if;
end;

我的general_exception变量是一个全局异常类型,位于我的两个程序所在的包中。

我想在第一个过程p1中捕获异常以避免执行其他事务。

我试过这个,但没有结果:

procedure p1(a in varchar2)
is 
begin 
  -- call second procedure
  p2(a);
  -- other things
exception when general_exception then
  dbms_output.put_line('ERROR');
end;

1 个答案:

答案 0 :(得分:3)

它适用于我(nb。我确实更改了你的p2来引用传入的参数,而不是静态值'1'!):

create or replace package test_pkg
as
  general_exception exception;

  procedure p1 (p_a in varchar2);
end test_pkg;
/

create package body test_pkg
as
  procedure p2 (p_a in varchar2)
  is
  begin
    if p_a = '2' then
      raise general_exception;
    end if;
  end p2;

  procedure p1 (p_a in varchar2)
  is
  begin
    p2(p_a);
    dbms_output.put_line('p2 executed sucessfully. Do all of the things.');
  exception
    when general_exception then
      dbms_output.put_line('ERROR');
  end p1;
end test_pkg;
/

set serveroutput on;

begin
  test_pkg.p1('1');
  test_pkg.p1('2');
end;
/

使用两个不同的值运行p1过程的输出是:

p2 executed sucessfully. Do all of the things.
ERROR

这是预期的。