Is a switch executing all the cases without stopping?

后端 未结 3 533
滥情空心
滥情空心 2020-12-20 01:31

I\'m on Java 8v60. I tried to embed a switch regarding an exception group in a catch block. Apparently, the case are recognised, but once they get into the switch, they keep

3条回答
  •  旧巷少年郎
    2020-12-20 01:50

    No. It's not a bug. You are not implemented switch properly. It's fall through. You need to have break after each case.

    For ex :

        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;
    

    Here is the official doc for the same

    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.

提交回复
热议问题