我在使用Java 8v60.我试图在catch块中嵌入一个关于异常组的开关.显然,案件得到了认可,但一旦他们进入交换机,他们就会继续经历所有可能的情况.这是一个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
}
...
很奇怪,不是吗.任何想法?
解决方法:
switch语句跳转到正确的值,并一直持续到其他情况结束.
如果你想退出switch语句,你必须使用一个中断(或在某些情况下返回).
这对于处理可以以相同方式处理许多值的情况很有用:
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;
}
如果案例选择也是方法的最终条件,则可以从中返回.
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;
}
}
}
标签:java,switch-statement
来源: https://codeday.me/bug/20191002/1841214.html