交换机是否在不停止的情况下执行所有情况? [英] Is a switch executing all the cases without stopping?

查看:112
本文介绍了交换机是否在不停止的情况下执行所有情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用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语句跳转到正确的值,并一直持续到其他情况结束。

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

如果你想退出switch语句,你必须使用休息(或在某些情况下返回)。

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;

    }
}



}

这篇关于交换机是否在不停止的情况下执行所有情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆