在switch语句中,当使用throw时,是否应该添加break?

huangapple go评论60阅读模式
英文:

Should I put a break after a throw in a switch statement?

问题

在一个switch case语句中,在使用throw后是否应该加上break?

选项1:

switch(value){
    case 1:
    case 2:
    case 3:
        throw APException();
        break;
    default:
        break;
}

选项2:

switch(value){
    case 1:
    case 2:
    case 3:
        throw APException();
    default:
        break;
}

我认为如果在throw后加上break会导致编译错误。所以,考虑选项2,这是一个可接受的解决方案吗?

英文:

Should I put a break after a throw in a switch case statement?

Option 1:

switch(value){
            case 1:
            case 2:
            case 3:
                throw APException();
                break;
            default:
                break;
        }

Option 2:

switch(value){
            case 1:
            case 2:
            case 3:
                throw APException();
            default:
                break;
        }

I think if I put a break after the throw it will give me a compile error. So, considering the Option 2, is this an acceptable solution?

答案1

得分: 3

throw 表达式

> ...将控制转移给具有与最近由此执行线程进入并且尚未退出的关键字 try 后面的复合语句或成员初始化列表匹配类型的异常处理程序。

因此,在 throw 后面,break 是无法到达的,因此 break 是不必要的(事实上,对于某些编译器,它会产生警告),因此应该省略。

英文:

A throw expression:

> ... transfers control to the exception handler with the matching type for which the compound statement or member initializer list that follows the keyword try was most recently entered and not exited by this thread of execution.

Therefore, the break is unreachable after the throw, making the break unnecessary (and, in fact, it produces a warning for some compilers), and so it should be omitted.

huangapple
  • 本文由 发表于 2023年6月29日 19:52:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580785.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定