duanhuang1967 2018-02-26 22:55
浏览 151
已采纳

PHP - 如果不满足条件,此代码是否可以保证停止?

I am only learning Exceptions and error reporting, and I am trying to understand behaviours of try/catch and perhaps other methods that I don't know yet. I have code like this:

function nameless(....) {
    if(!$condition) {
        throw new Exception('Condition not met');
    }
    [someCode ...]
    return $result;
}

I want to make sure that someCode only executes if the condition is met. Would a structure like this guarantee that it?

Before talking about putting the rest of the code in an else block, or other methods, I want to know if there is some way to execute nameless() in a way that would continue its execution after it throws the exception.

Once I know that, I would like to know if there are better/worse ways of doing things and if this particular example is poor or it's one of a hundred equally valid ways to do this. Thank you.

  • 写回答

1条回答 默认 最新

  • douduoquan2824 2018-02-26 23:06
    关注

    Yes, it will stop. The behavior is defined here:

    When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

    Based on the definition and purpose of exceptions, the function should not continue after an exception, and you shouldn't look for a way to force that to happen.

    If you have some code that must be executed even after an exception is thrown, you should not include it in the function, but instead enclose the function in a try/catch, with the necessary code in a finally block.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?