开关是否在不停歇地执行所有案例?
我使用的是 Java 8v60.我试图在 catch 块中嵌入关于异常组的开关.显然,案件已得到认可,但一旦他们进入交换机,他们就会继续处理所有可能的案件.这是 Java 错误吗?
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?
看起来像这样:
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?
推荐答案
switch语句跳转到正确的值,并继续到其他case结束.
The switch statements jump to the right value, and continue up to the end of other cases.
如果您想退出 switch 语句,您必须使用 break(或在某些情况下返回).
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;
}
}
}
相关文章