Java – can you use throw instead of break in a switch statement?

Can I throw or exit a switch statement without using the break keyword? Why use throwing instead of rest?

switch(number)
{
    case 1:
        throw new RuntimeException("Exception number 1");
    case 2:     
        throw new RuntimeException("Exception number 2"); 
}

Solution

There are two situations in which throw can be used to interrupt the traffic of the switch:

>Flow control; In general, this is a bad practice – you don't want special behavior to determine where your plan will go next. > Unlikely but plausible default; If you reach a condition that cannot reach the default value, it will happen anyway Somehow Incredible Or, if you have strict coding standards, you require switch statements to have defaults

Example:

public class Test {
    public static enum Example {
        FIRST_CASE,SECOND_CASE;
    }
    public void printSwitch(Example theExampleCase) {
        switch(theExampleCase) {
            case FIRST_CASE:
                System.out.println("First");
                break;
            case SECOND_CASE:
                System.out.println("Second");
                break;
            default:  // should be unreachable!
                throw new IllegalStateException(
         "Server responded with 724 - This line should be unreachable");
     }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>