这个问题是关于对try块外运行的代码只有在没有抛出异常的最好的办法。干净的方法只有在没有抛出异常
try {
//experiment
//can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
//contain the blast
} finally {
//cleanup
//this is not the answer since it executes even if an exception occured
//finally will be available in php 5.5
} else {
//code to be executed only if no exception was thrown
//but no try ... else block exists in php
}
这方法通过@webbiedave响应于问题php try .. else建议。我发现它不令人满意,因为使用了额外的$caught
变量。
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
那么什么是更好的(或最好的)方式来完成这个,而不需要额外的变量呢?
把它放在try块。如果它可能抛出另一个你不想被外部try块捕获的异常,那么使用一个嵌套的try-catch来捕获该异常。但请注意,您不会将异常用作流量控制。 – ssube
@peachykeen这将无法正常工作,因为异常需要冒泡。 –
听起来很像你使用异常来控制执行过多。你确定你需要扔砖块和后面的冒泡吗?很可能的是,例外*应该被变量和适当的流量控制所取代。 – ssube