donglu8779 2019-07-13 16:22
浏览 380
已采纳

在PHP中使用try-catch如何在没有抛出异常的情况下最终进入?

About the following code, how can I go to finally without throw an Exception in 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条回答 默认 最新

  • douyi2664 2019-07-13 16:37
    关注

    Please don't do this, but here's an option:

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

    I strongly encourage against using a goto. I think it's just really easy for code to get sloppy & confusing if you're using goto.

    I'd recommend:

    try {
        if (TRUE){
            echo "
    That's better";
        } else {
           echo "
    did not break";
        }
    } catch (Exception $e){
        echo "
    did catch";
    } finally {
        echo "
    i'm so tired";
    }
    

    You just wrap the rest of the try into an else in order to skip it.


    Another option could be to declare a finally function, call that, and return.

    //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 "
    did not break";
    } catch (Exception $e){
        echo "
    did catch";
    } finally {
        $doFinally();
    }
    

    If you needed to continue the script, you could declare $doFinally something like:

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

    Then after the finally block, you could call $doFinally(TRUE) to reset it for the next try/catch

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大