【问题标题】:When and why can `finally` be useful?`finally` 何时以及为何有用?
【发布时间】:2014-05-01 02:28:41
【问题描述】:

PHP 5.5 已实现 finallytry-catch。我的疑问是:什么时候try-catch-finally 可能比我在try-catch 下方写的更有帮助?

例子,区别:

try { something(); }
catch(Exception $e) { other(); }
finally { another(); }

而不是,只是:

try { something(); }
catch(Exception $e) { other(); }
another();

可以发给我一些本案常见的例子吗?

注意事项

  1. 我只谈论try-catch-finally,而不是try-finally
  2. 有一些“功能”很酷,比如取消当前异常并最终抛出新的其他异常(我没试过,I read here)。我不知道没有finally是否可以;
  3. notcatch 这样的东西不是更有用吗?因此,如果try 没有异常,我可以运行代码。呵呵

【问题讨论】:

  • 无论是否发生异常都需要发生某些事情时。
  • finally 块将总是被执行,而try-catch 之后的普通代码可能不会,在从方法或类似方法返回的情况下。这使您可以清理任何必要的东西,例如资源使用情况。
  • @Vulcan 所以如果我这样做try { return something(); } finally { other(); }other() 会运行吗?如果我做finally { return other(); },会返回什么?有可能吗?
  • @Vulcan 关于研究,我在 Google 和 SO 上做了很多工作,但我发现更多与 Java 相关,而且我喜欢了解 PHP。例如,Java 支持线程,最后似乎即使线程退出也能工作,类似的事情。我真的不知道Java。 :)
  • @DavidRodrigues finally 块中返回的值将是函数返回的实际值。

标签: php exception-handling try-catch-finally


【解决方案1】:

您可能无法捕获您正在抛出的异常,但您仍然希望在抛出错误之前运行您的finally 语句(例如,始终关闭日志文件或数据库连接,因为您没有捕获到致命失败之前)例外):

<?php

$fHandle = fopen('log.txt', 'a');

try {
    echo 'Throwing exception..';
    fwrite($fHandle, 'Throwing exception..');

    throw new BadFunctionCallException();
} catch (RangeException $e) {
    // We only want to log RangeExceptions

    echo 'Threw a RangeException: ' . $e->getMessage();
    fwrite($fHandle, 'Threw a RangeException: ' . $e->getMessage());
} finally {
    // Always make sure that we close the file before throwing an exception, even if we don't catch it

    echo 'Reached the finally block';
    fwrite($fHandle, 'Reached the finally block');
    fclose($fHandle);
}

哪个会输出:

Throwing exception..Reached the finally block
Fatal error: Uncaught exception 'BadFunctionCallException' in /tmp/execpad-dc59233db2b0/source-dc59233db2b0:6
Stack trace:
    #0 {main}
    thrown in /tmp/execpad-dc59233db2b0/source-dc59233db2b0 on line 6

DEMO (without the fopen as eval.in doesn't support it)

【讨论】:

    【解决方案2】:

    finally 块中的代码总是在离开 trycatch 块后执行。当然你可以在 try-catch 之后继续写代码,它也会被执行。但是,当您想中断代码执行(例如从函数返回、中断循环等)时,finally 可能会很有用。您可以在此页面上找到一些示例 - http://us2.php.net/exceptions,例如:

    function example() {
      try {
         // open sql connection
         // Do regular work
         // Some error may happen here, raise exception
      }
      catch (Exception $e){
        return 0;
        // But still close sql connection
      }
      finally {
        //close the sql connection
        //this will be executed even if you return early in catch!
      }
    }
    

    但是,是的,你是对的; finally 在日常使用中不是很受欢迎。当然不如单独尝试捕获。

    【讨论】:

    • 您的示例涵盖了try-finally 的情况,但问题指定只询问有关try-catch-finally 的信息。
    • 更新了示例,使其更加具体。谢谢!
    • 是的,肯定的!自从你问后刚刚测试过:D
    • 很有趣,嗯 :) +1 努力。
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多