Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is actively throwing AssertionError in Java good practice? [duplicate]

Tags:

java

assertion

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 Errorhere, but if we want to throw an Exception or an Error, which one should it be? And is it good practice to actively throw AssertionErrors? 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)

like image 526
Mathias Bader Avatar asked Dec 25 '16 18:12

Mathias Bader


People also ask

Which statement is true about AssertionError class?

An AssertionError thrown as a result of a failed assertion should always be handled by the enclosing method. Explanation: Option A is correct. Because assertions may be disabled, programs must not assume that the boolean expressions contained in assertions will be evaluated.

How do you handle Java Lang AssertionError?

In order to handle the assertion error, we need to declare the assertion statement in the try block and catch the assertion error in the catch block.

What causes Java Lang AssertionError?

As with many other languages, the AssertionError in Java is thrown when an assert statement fails (i.e. the result is false).

Is it a good practice to use assert in Java?

Yes it is a very good practice to assert your assumptions. Read Design By Contract. assert can be used to verify pre conditions, invariants and post conditions during integration and testing phases. This helps to catch the errors while in development and testing phases.


1 Answers

I would agree with Mr. Bloch here - the alternatives (IllegalArgumentException, IllegalStateException, and UnsupportedOperationException) do not properly convey the severity of the issue, and callers may erroneously try to catch and handle this case. In fact if this line is ever reached the program in question is broken, and the only sane thing to do is exit.

The point here is that enum has a finite set of values, thus it should be impossible to reach the throw line - it would only occur if the enum's definition has changed without also fixing this instance method. Throwing a RuntimeException suggests the caller made a mistake, when in fact the method (and the enum) itself is broken. Explicitly raising an AssertionError correctly indicates the invariants this method expects have been violated.

Guava has a helpful article which breaks down when to raise different types of exceptions. They write:

A conventional assertion is a check that should only fail if the class itself (that contains the check) is broken in some way. (In some cases this can extend to the package.) These can take various forms including postconditions, class invariants, and internal preconditions (on non-public methods).

An impossible-condition check is one that cannot possibly fail unless surrounding code is later modified, or our deepest assumptions about platform behavior are grossly violated. These should be unnecessary but are often forced because the compiler can't recognize that a statement is unreachable, or because we know something about the control flow that the compiler cannot deduce.

The page says an AssertionError is the recommended way to handle these cases. The comments in their Verify class also offers some useful insights about choosing exceptions. In cases where AssertionError seems too strong raising a VerifyException can be a good compromise.

As to the specific question of Error or RuntimeException, it doesn't really matter (both are unchecked and therefore will potentially travel up the call stack without being caught), but callers are more likely to attempt to recover from a RuntimeException. Crashing the application in a case like this is a feature, because otherwise we're continuing to run an application that is (at this point) demonstrably incorrect. It's certainly less likely that callers will catch and handle AssertionError (or Error or Throwable), but of course callers can do whatever they want.

like image 102
dimo414 Avatar answered Sep 20 '22 22:09

dimo414