Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

java - Is a switch executing all the cases without stopping?

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 going through all the possible cases. Is this a Java bug?

It looks like this:

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
}
...

Weird, isn't it. Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...