这个问题是关于最好的方法,只有在没有抛出异常的情况下才能在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) {
}
那么在不需要额外变量的情况下实现这一目标的更好(或最好)方法是什么?
答案 0 :(得分:5)
一种可能性是将try块放在方法中,如果异常是正确的,则返回false。
function myFunction() {
try {
// Code that throws an exception
} catch(Exception $e) {
return false;
}
return true;
}
答案 1 :(得分:0)
让你的catch块退出函数或(重新)抛出/抛出异常。您也可以过滤您的例外情况。因此,如果您的其他代码也抛出异常,您可以捕获它并(重新)抛出它。请记住:
我处理你的情况的方法是(重新)从第二个语句中抛出异常。
try {
$this->throwExceptionA();
$this->throwExceptionB();
} catch (Exception $e) {
if($e->getMessage() == "ExceptionA Message") {
//Do handle code
} elseif($e->getMessage() == "ExceptionB Message") {
//Do other clean-up
throw $e;
} else {
//We should always do this or we will create bugs that elude us because
//we are catching exception that we are not handling
throw $e;
}
}