【发布时间】:2013-06-17 00:38:02
【问题描述】:
PHP 5.5 在 try/catch 块中添加了对 finally 的支持。
Java 允许您创建一个没有 catch 块的 try/catch/finally 块,因此您可以在发生异常时在本地进行清理,但让异常本身传播到调用堆栈以便单独处理。
try {
// Do something that might throw an exception here
} finally {
// Do cleanup and let the exception propagate
}
在当前版本的 PHP 中,您可以实现对异常进行清理并让它传播的功能,但如果没有抛出异常,则永远不会调用清理代码。
try {
// Do something that might throw an exception here
} catch (Exception $e) {
// Do cleanup and rethrow
throw $e;
}
PHP 5.5 会支持 try/finally 样式吗?我已经在寻找这方面的信息,但我能从 PHP.net 找到最接近答案的信息,只暗示它没有。
在 PHP 5.5 及更高版本中,finally 块也可以在 抓块。 finally 块中的代码将始终被执行 在 try 和 catch 块之后,无论是否有异常 被抛出,并且在正常执行恢复之前。
措辞表明您总是希望有一个 catch 块,但据我所知,它并没有直接说明它。
【问题讨论】:
标签: php exception exception-handling