When performing "sanity checks" at runtime, what is the best built-in Exception
to throw to indicate a logic error? InternalError
is tempting, but as an Error
my understanding is that it should only be use to indicate problems in the JVM itself, not application logic errors. Right now I tend to throw RuntimeException
s, but I find that distasteful because the type is so general. Is there a more specific type I should be using?
I'm avoiding using assert
for these checks because they should still be performed in production. For this reason, "you should be using assert
" is not The Right Answer.
I apologize for the subjective nature of this question, but I'm hoping there are some well-known best practices that I'm just not aware of.
EDIT: Here's a good example of what I'm talking about, although certainly there are other good examples and the idea is more general:
public static void foobar(ModelObject o) {
switch(o.getEnumProperty()) {
case ENUMVALUE1:
// Handle...
break;
case ENUMVALUE2:
// Handle...
break;
default:
// In theory, this should never be reached. The code should handle any
// enum value it's Java-legal for the code to pass. But, if a new
// enum value is added and this code is not updated, this WILL be
// reached. This is not an IllegalArgumentException because the caller
// passed a valid value -- remember, we SHOULD handle any enum value
// here -- but the code has not been updated. For this reason, it's an
// "internal error" of sorts. However, there's no good "my program's
// logic is broken" Exception that I know of built into the JRE. It is
// this Exception that I'm looking for in this question.
//
// Hopefully this clarifies the question somewhat.
throw new RuntimeException("Unhandled: "+o.getType());
}
}
I suppose a more specific way to phrase this question would be "What kind of Exception should I throw if there is code that should never be reached, but GETS reached, in a production environment?" This is not precisely the right question, but all "sanity checks" can be "spelled" in terms of code that should never be reached, so it's close enough.