Is a switch executing all the cases without stopping?(开关是否在不停歇地执行所有案例?)
问题描述
我使用的是 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;
}
}
}
这篇关于开关是否在不停歇地执行所有案例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:开关是否在不停歇地执行所有案例?


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01