Search code examples
javaswitch-statementassert

Combining assert and switch statements


I was answering a Java test and come across the question:

Which of the following statements is true?

A. In an assert statement, the expression after the colon ( : ) can be any Java expression.

B. If a switch block has no default, adding an assert default is considered appropriate.

C. In an assert statement, if the expression after the colon ( : ) does not have a value, the assert's error message will be empty.

D. It is appropriate to handle assertion failures using a catch clause.

The right answer is B. To be honest, I answered that question by excluding another obviously wrong cases, but I can't get the point of that question actually. Could anyone explain why it is true? Where can it be helpful?


Solution

  • I guess it means you should protect yourself from missing a switch case.

    Say you have an enum Color {red, green} and this switch in the code:

    switch(color) {
       case red: 
           doSomethingRed();
           break;
       case green: 
           doSomethingGreen();
           break;
    }   
    

    If in the future you add a new color blue, you can forget to add a case for it in the switch. Adding failing assert to the default case will throw AssertionError and you will discover your mistake .

    switch(color) {
       case red: 
           doSomethingRed();
           break;
       case green: 
           doSomethingGreen();
           break;
       default: 
           assert false : "Oops! Unknown color"
    }