Is a switch executing all the cases without stopping?

后端 未结 3 518
滥情空心
滥情空心 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:47

    Its not java bug. It's your logical bug.

    put break statement after each case statement to avoid fall through situation.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-20 01:54

    The switch statements jump to the right value, and continue up to the end of other cases.

    If you like to exit the switch statement you have to use a break (or return in some situations).

    This is useful to handle situations in wich many values can be handled at the same manner:

    switch (x) {
        case 0:
        case 1:
        case 2:
            System.out.println("X is smaller than 3");
            break;
        case 3:
            System.out.println("X is 3");
        case 4:
            System.out.println("X is 3 or 4");
            break;
    }
    

    If the case selection is also a final condition for a method you can return from it.

    public String checkX(int x) {
        switch (x) {
        case 0:
        case 1:
        case 2:
            return "X is smaller than 3";
        case 3:
            return "X is 3";
        case 4:
            return ("X is necessary 4");
        default:
            return null;
    
        }
    }
    
    
    
    }
    
    0 讨论(0)
提交回复
热议问题