Looking through Joshua Bloch's 'Effective Java - Second Edition', I stumbled upon the following code on page 152:
double apply(double x, double y) {
switch(this) {
case PLUS: return x + y;
case MINUS: return x - y;
case TIMES: return x * y;
case DIVIDE: return x / y;
}
throw new AssertionError("Unknown op: " + this);
}
Now what confuses me is, that the AssertionError
is actively thrown. Is that considered good practice?
To my understanding assertions are used to not interfeer with the code such that when the java programming is started without assertions enabled and the assert-statements are therefore not executed, the behavior doesn't change.
I would be rather confused, if I'd get a AssertionException
when I run a program without even having assertions enabled.
Even though I understand that the example case might happen quite often, that you analyze a couple of different options and if it is none of them, you should throw an exception.
So is it good practice to throw an AssertionException
here, or would it be better to throw a different one? If so, which one would fit best? Maybe IllegalArgumentException
?
Edit for clarification: My question is not about whether we should throw an Error
here, but if we want to throw an Exception
or an Error
, which one should it be? And is it good practice to actively throw AssertionError
s? The documentation says Thrown to indicate that an assertion has failed, so I have the feeling that we should not actively throw it. Is that correct?
Second Edit: Clear question: Is it good practice to actively throw an AssertionError
, or should that be avoided, even though it is possible? (My guess reading the docs is the latter)