Can throw be used instead of break in a switch statement?

Jerry picture Jerry · May 16, 2013 · Viewed 14.1k times · Source

Can throw also be used to exit switch statement without using break keyword? Why use a throw instead of break?

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

Answer

Makoto picture Makoto · May 16, 2013

There are two cases in which you could use a throw to interrupt the flow of a switch:

  1. Flow Control; in general, this is a bad practice - you don't want exceptional behavior deciding where your program decides to go next.

  2. Unlikely-but-plausible default case; in case you hit a condition in which reaching the default should be impossible, but happens anyway. Somehow. Miraculously. Or, if you have strict coding standards, which mandate that switch statements have a default case.

    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");
         }
    }