php中finally不能用,php-什么时候以及为什么`finally`有用?
PHP 5.5最終實現了try-catch.我的疑問是:到底何時進行try-catch-find可能比僅在try-catch下方編寫更有用?
示例之間的區別:
try { something(); }
catch(Exception $e) { other(); }
finally { another(); }
取而代之的是:
try { something(); }
catch(Exception $e) { other(); }
another();
能給我提供一些這種情況下常見的例子嗎?
筆記:
>我只說說try-catch-finally,而不是說說try-finally.
>有些“功能”很酷,比如您取消當前的異常并最終拋出一個新的其他異常(我沒有嘗試過,I read here).我不知道是否有可能最終實現.
>諸如notcatch之類的東西有用嗎?因此,如果嘗試無一例外,我可以運行代碼.呵呵
解決方法:
在try或catch塊離開后,finally塊中的代碼始終執行.當然,您可以在try-catch之后繼續編寫代碼,它也會被執行.但是,當您想中斷代碼執行時(例如從函數返回,中斷循環等),最后還是很有用的.您可以在此頁面上找到一些示例-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!
}
}
但是,是的,你是對的.最后在日常使用中不是很流行.當然,不如單獨嘗試捕獲.
標簽:try-catch-finally,php,exception-handling
來源: https://codeday.me/bug/20191010/1887977.html
總結
以上是生活随笔為你收集整理的php中finally不能用,php-什么时候以及为什么`finally`有用?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php laravel组件,php –
- 下一篇: linux ksh怎么查找僵尸进程,Un