📜 ⬆️ ⬇️

Finally, PHP 5.5 may appear.

Not so long ago, Nikita Popov, one of the activists of the movement "FOR PHP", posted a message on his twitter:

PHP 5.5 will have finally t.co/Dy93CZaR

(The original is here twitter.com/nikita_ppv/status/232930291625369600 )

Further, free translation:

Representation


In this release of the RFC, we will try to introduce you to support for the new " finally " keyword in exceptions.
')
Without this feature, developers often have to write constructions of the form:
<?php $db = mysqli_connect(); try { call_some_function($db); } catch (Exception $e) { mysqli_close($db); throw $e; } mysql_close($db); 


With the introduction of finally , we do not say that you have to write less code, we say that you will get more opportunities to manage try / catch structures

Sentence


The finally block is always executed when the try / catch block is completed.
This means that the finally block is executed even if an exception has been thrown. Finally , however, is actually more useful than simple exception handling. It allows programmers to avoid unnecessary constructions for cleaning memory and / or connections at the time of exception handling or if they were not caught.

 <?php $db = mysqli_connect(); try { call_some_function($db);//    ,       } finally { mysqli_close($db); } 

The delicate moment when using a new construct is to use the return construct in a try / catch block ; in this case, the finally block will still be called.

 <?php try { return 2; } finally { echo "   \n"; } //    echo "    "; 

the result will be:


//return int(2)

Well, in the case of nested try / catch / finally constructs :

 <?php function foo ($a) { try { echo "1"; try { echo "2"; throw new Exception("ex"); } catch (Exception $e) { echo "3"; } finally { echo "4"; throw new Exception("ex"); } } catch (Exception $e) { echo "3"; } finally { echo "2"; } return 1; } var_dump(foo("para")); 

we will receive:

123432int(1)

Tests and Examples


There are also many examples and cases, you can peep further.

https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_001.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_002.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_003.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_004.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_005.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/catch_finally_006.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/try_finally_001.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/try_finally_002.phpt
https://github.com/laruence/php-src/blob/finally/Zend/tests/try_finally_003.phpt

Source: https://habr.com/ru/post/149314/


All Articles