java - 交换机是否会不停地执行所有情况?

标签 java switch-statement

我使用的是 Java 8v60。我尝试在 catch block 中嵌入有关异常组的开关。表面上,案件已经被认可,但一旦他们进入开关,他们就会不断地检查所有可能的案件。这是 Java 错误吗?

看起来像这样:

try {
    ... 
} catch (DateTimeParseException exc) {
    ...
} catch (myException exc) {
switch (exc.getEvent()) {
    case EVENT_ONE :
//once EVENT_ONE gets here;
    case EVENT_TWO : case EVENT_THREE :
//it keeps going everywhere;
    case EVENT_FOUR :
//and so on;
    default :
//and here of course too.
//but if it's not one of the above, it just appears here only
}
...

很奇怪,不是吗?有什么想法吗?

最佳答案

没有。这不是一个错误。您没有正确实现切换。已经摔倒了在每个案例之后,您都需要break

例如:

    switch (exc.getEvent()) {
    case EVENT_ONE :
    //once EVENT_ONE gets here;
    break;
    case EVENT_TWO : case EVENT_THREE :
   //it keeps going everywhere;
    break;
    case EVENT_FOUR :
   //and so on;
    break;

这是official doc对于相同的

Another point of interest is the break statement. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

关于java - 交换机是否会不停地执行所有情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32438403/

相关文章:

java - 用 jai 创建马赛克

java - 如何在 Mac OS X 10.9 上加速 IntelliJ

Java、switch case 和数组

Java SQL异常: Closed Resultset: next even though neither connection or resultset gets closed

Java switch 语句多例

java - 使用查询缓存时,Hibernate 执行 N+1 个选择而不是 1 个查询

java - 一个大的 switch 语句还是几个小的 switch 语句?

javascript - Javascript 中的动态切换

javascript - 在 JavaScript 中使用 switch 语句编写 if..else 语句

c# - 通过 switch 语句掉线(有时有效?)