Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.5 and try ... finally

PHP 5.5 is adding support for finally in try/catch blocks.

Java allows you to create a try/catch/finally block with no catch block, so you can cleanup locally when an exception happens, but let the exception itself propagate up the call stack so it can be dealt with separately.

try {
    // Do something that might throw an exception here
} finally {
    // Do cleanup and let the exception propagate
}

In current versions of PHP you can achieve something that can do cleanup on an exception and let it propagate, but if no exception is thrown then the cleanup code is never called.

try {
    // Do something that might throw an exception here
} catch (Exception $e) {
    // Do cleanup and rethrow
    throw $e;
}

Will PHP 5.5 support the try/finally style? I have looked for information on this, but the closest I could find to an answer, from PHP.net, only implies that it doesn't.

In PHP 5.5 and later, a finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

The wording suggests that you're always expected to have a catch block, but it doesn't state it outright as far as I can see.

like image 332
GordonM Avatar asked Jun 20 '13 08:06

GordonM


2 Answers

Yes, try/finally is supported (RFC, live code). The documentation is indeed not very clear and should be amended.

like image 84
Jon Avatar answered Sep 20 '22 03:09

Jon


I've implemented a test case on a 5.5RC3 server.

As you can see in the code, it works as expected. Documentation is indeed wrong at this point.

like image 20
Niels Keurentjes Avatar answered Sep 18 '22 03:09

Niels Keurentjes