在PHP中使用try-catch如何在不引发异常的情况下最终到达?

时间:2019-07-13 16:22:20

标签: php

关于以下代码,如何在不抛出PHP异常的情况下最终进入?

try {
  $db = DataSource::getConnection();
  if (some condition here is TRUE) { 
     // go to finally without throw an exception 
  }
  $stmt = $db->prepare($sql);
  $stmt->saveMyData();
} catch (Exception $e) {
  die($e->getMessage());
} finally {
  $db = null;
}

1 个答案:

答案 0 :(得分:0)

请不要这样做,但这是一个选择:

try {
    if (TRUE){
        goto ugh;
    }
    echo "\ndid not break";
    ugh:
} catch (Exception $e){
    echo "\ndid catch";
} finally {
    echo "\ni'm so tired";
}

我强烈建议您不要使用goto。我认为,如果您使用的是goto,那么代码变得很草率和混乱就非常容易。

我建议:

try {
    if (TRUE){
        echo "\nThat's better";
    } else {
       echo "\ndid not break";
    }
} catch (Exception $e){
    echo "\ndid catch";
} finally {
    echo "\ni'm so tired";
}

您只需将try的其余部分包装到else中即可跳过


另一种选择是声明一个finally函数,然后调用它并返回。

//I'm declaring as a variable, as to not clutter the declared methods
//If you had one method across scripts, naming it `function doFinally(){}` could work well
$doFinally = function(){};
try {
    if (TRUE){
        $doFinally();
        return;
    }
    echo "\ndid not break";
} catch (Exception $e){
    echo "\ndid catch";
} finally {
    $doFinally();
}

如果您需要继续执行脚本,则可以声明$doFinally像这样:

$doFinally = function($reset=FALSE){
    static $count;
    if ($reset===TRUE){
        $count = 0;
        return;
    } else if ($count===NULL)$count = 0;
    else if ($count>0)return;
}

然后在finally块之后,可以调用$doFinally(TRUE)将其重置为下一个try / catch