I have the following code
public enum Animal {
DOG,CAT;
private void exitWithError(String message){
System.out.println(message);
System.exit(1);
}
@Override
public String toString() {
switch(this){
case DOG:
return "dog";
case CAT:
return "cat";
default:
// missing return statement error
exitWithError("unrecognized animal");
/*
workaround - don't like it
return null;
*/
/* no error if exception thrown
throw new IllegalStateException("unrecognized animal");
*/
}
}
}
The above code results in a missing return statement
error. I have some questions:
The
exitWithError
method should always finish program execution, right?If the method always exits, is there any way I can inform the compiler about it so it doesn't throw the
missing return statement
at me?
The return null
workaround seems to be bad code as if the code changed and this return statement would get executed it could cause problems.