什么时候,为什么“终于”有用? [英] When and why can `finally` be useful?

查看:140
本文介绍了什么时候,为什么“终于”有用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP 5.5已经实现了 finally try-catch 。我的疑问是:当完全 try-catch-finally 可能比以下写的更有帮助 try-catch

PHP 5.5 has implemented finally to try-catch. My doubt is: when exactly try-catch-finally that might be more helpful than just I write below try-catch?

示例:

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

而不是仅仅:

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

可以给我一些这种情况的常见例子吗?

Can send me some example that is common to this case?

注意


  1. 我谈论 try-catch-最后,而不是关于 try-finally ,只有;

  2. 有一些功能像你取消当前的异常,最后抛出一个新的其他异常(我没有尝试,我在这里阅读)。我不知道是否可能没有终于;

  3. 不会像 notcatch ?所以我可以运行代码,如果尝试没有例外。 hehe

  1. I talk about try-catch-finally, and not about try-finally, only;
  2. There are some "features" cool, like you cancel current exception and throw a new-other-exception on finally (I don't tried, I read here). I don't know if it is possible without finally;
  3. Would not be more useful something like notcatch? So I can run a code if try goes without an exception. hehe


推荐答案

中的代码终于块始终在从 try catch 块退出后执行。当然,您可以继续在try-catch之后编写代码,并且也将执行。但是,当您想要突破代码执行(例如从函数返回,突破循环等)时,最终可能会有用。您可以在此页面上找到一些示例 - http://us2.php.net/exceptions ,例如:

The code within the finally block is always executed after leaving from either try or catch blocks. Of course you may continue writing code after the try-catch and it will be executed as well. But finally could be useful when you'd like to break out of code execution (such as returning from a function, breaking out of a loop etc.). You can find some examples on this page - http://us2.php.net/exceptions, such as:

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!
  }
}

但是,你是对的; 终于在日常使用中不是非常受欢迎。当然不如try-catch一样多。

But yes, you are right; finally is not very popular in everyday use. Certainly not as much as try-catch alone.

这篇关于什么时候,为什么“终于”有用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆