PHP 5.5 and try … finally

时光毁灭记忆、已成空白 提交于 2019-12-23 07:29:25

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/17208838/php-5-5-and-try-finally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!