什么时候,为什么“终于”有用?
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?
注意:
- 我谈论
try-catch-最后
,而不是关于try-finally
,只有; - 有一些功能像你取消当前的异常,最后抛出一个新的其他异常(我没有尝试,我在这里阅读)。我不知道是否可能没有
终于
; - 不会像
notcatch
?所以我可以运行代码,如果尝试
没有例外。 hehe
- I talk about
try-catch-finally
, and not abouttry-finally
, only; - 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
; - Would not be more useful something like
notcatch
? So I can run a code iftry
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.