douzhi7451 2018-08-17 16:07
浏览 119

PHP - 具有异常的Switch Case

I am wondering if I should include break in my switch even if a case is throwing an exception.

switch ($key) {
    case self::ABC:
    case self::CBA:
        if (!is_string($key)) {
            throw new Exception('Well.. this should be a string my friend');
        }
        break;
}

Am I even getting to the break? I do not think so, so why should I include it? Does it makes sense?

  • 写回答

1条回答 默认 最新

  • duanan6043 2018-08-17 17:07
    关注

    If self::CBA is a string, then the exception won't be thrown and your code will reach to break. If that case is the last case in your switch, then break may not be needed as the switch will end anyways, but it is better to just add break instead of not adding it, it's one line of code that can save you a lot of trouble from executing codes that were not meant to be executed. I know this the hard way.

    By adding break to all cases, you can rearrange the cases without any problems in the future and you would also get into the habit of writing break every time you write a switch statement (it's a good habit). I hope it answers your question.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料