繁体   English   中英

在PHP中使用try-catch如何最终不引发异常?

[英]Using try-catch in PHP how to go to finally without throw an Exception?

关于以下代码,如何在不抛出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;
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM