【问题标题】:Similar to finally Block (JAVA) in Oracle PL/SQL Block类似于 Oracle PL/SQL 块中的 finally Block (JAVA)
【发布时间】:2017-11-23 07:36:09
【问题描述】:

在 Java 中,finally 块在所有条件下都执行。

Oracle PL/SQL 中是否有任何类似的函数,只要过程完成执行,即使使用了 return 语句也会执行?

【问题讨论】:

标签: oracle plsql oracle11g


【解决方案1】:

没有 FINALLY 的等价物,但您可以使用嵌套的 PL/SQL 块来模拟它;

DECLARE
  -- Your variables.
  return_early BOOLEAN := FALSE;
BEGIN
  -- Do something

  DECLARE
    -- Local variables in "try" block
  BEGIN 
    -- Equivalent of "try" block
    -- Do something that may raise an exception
    IF some_condition THEN
      return_early := TRUE;
      -- you could also use "GOTO end_try;" rather than surrounding the
      -- following statements in an "ELSE" statement
    ELSE
      -- Do something else that may raise an exception
    END IF;
  EXCEPTION
    WHEN your_exception THEN
      -- Equivalent of "catch" block
  END;
  <<end_try>>
  -- Handle "finally" here, after end of nested block.
  -- Note: you can only see variables declared in this outer block
  --       not variables local to the nested PL/SQL block.
  IF return_early THEN
    RETURN;
  END IF;

  -- Continue and do more stuff.
END;
/

【讨论】:

  • 如果在“try”块中引发未处理的异常,这个“finally”部分将不会运行。
  • @DavidBalažic 如果您对此感到担心,请将WHEN OTHERS THEN ... 添加到异常处理块中以处理其他未捕获的异常。
【解决方案2】:

Stackoverflow 上的另一个帖子可以在这里提供帮助:Exception handling in pl/sql

Tony 说:

"您可以创建嵌套块:"

create or replace procedure Trial
    is 
Begin
  begin
    ---Block A--
  EXCEPTION
    when others then
      insert into error_log values('error');
  end;
  begin
    --Block B ----
  end;
end;

【讨论】:

    【解决方案3】:

    您可以创建一个自定义异常,然后在其他异常结束时引发它,此自定义异常必须位于外部块上:

    BEGIN
        BEGIN
         --DO SOME CODE HERE
        EXCEPTION 
          WHEN NO_DATA_FOUND THEN
            --HANDLE EXCEPTION
            RAISE CUSTOM_EXCEPTION;
        END;
    EXCEPTION
        WHEN CUSTOM_EXCEPTION THEN
          --HANDLE THE FINALLY CODE HERE
    END;
    

    【讨论】:

      猜你喜欢
      • 2012-01-04
      • 1970-01-01
      • 2011-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2013-01-05
      相关资源
      最近更新 更多