(This question isn't about how it can be done, but rather how it should be done.)
I'm implementing a program that creates a decision tree. There are different ways the tree can be constructed, so I have a static variable 'type' that is assigned in the main function. In the Node class constructor, I have a switch statement that checks the value of this type variable and does something accordingly.
I want to know the best way to handle the case in which the value does not match any of the preset options (the 'default' case). This should be impossible and will probably never be executed, but I want to do it right nonetheless. If this case does happen, I want it to print a message and terminate the program.
I know I can do it by simply throwing an error there and catching it the main, but it doesn't seem intuitive for something that should never happen. Is "System.exit(1)," what I need?
public class Node {
// some attributes
public static int type;
public static final int TYPE1 = 0;
public static final int TYPE2 = 1;
public Node(**arguments**){
// do some stuff first
switch(this.type){
case Node.TYPE1:
splitType1();
break;
case Node.TYPE2:
splitType2();
break;
default:
// unrecognized type
System.err.print("Error: Unrecognized type");
System.exit(1);
}
// do some more stuff
}
}
Throw an exception and don't catch it. Let it propagate all the way up. If something you consider to be impossible has happened, then you should have no confidence at all in your ability to "handle" it... the world is hugely screwed up.
IllegalStateException
is somewhat appropriate for this, although you might also want to consider using AssertionError
, if it's really that impossible. (Consider whether you want any code that catches plain Exception
to try to handle this situation - if not, Error
is appropriate.)
In this case, given that you've got a public static variable, it seems entirely feasible for any code to change this and put it in an invalid state. IllegalStateException
is therefore more reasonable.
If, however, you changed the code so that the variable was private, and the methods which changed its value all validated that the value became either 0
or 1
before setting it, then an AssertionError
would be more appropriate.
(I'd personally use an enum for something that can be one of a fixed set of values, mind you. That limits the ability of this to get messed up...)
See more on this question at Stackoverflow