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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题