12.9.2. Control Flow Assertions
You can also use assertions to verify that the control flow of some code is always what you want it to be:
// value must always be present
private void replace(int val, int nval) {
for (int i = 0; i < values.length; i++) {
if (values[i] == val) {
values[i] = nval;
return;
}
}
assert false : "replace: can't find " + val;
}
This loop should never reach the end, because some index in the loop ought to cause a return. If this doesn't
happen, the loop will unexpectedly fall out the bottom and the program will continue silently on its
unexpected way. The assertfalse after the loop means that if the control flow ever gets there you will be
told.
In this kind of case you can reasonably avoid the assertion mechanism entirely and go straight to throwing the
error yourself, replacing the assert with a throw:
throw new AssertionError("replace: can't find " + val);
Using a tHRow is especially valuable for methods that return values. Without a throw the compiler would
not know that the method cannot get to the bottom, so it insists that you return a value at the end. That code
typically looks like this:
return -1; // never happens
The comment "never happens" asserts something to be true but doesn't check or enforce it. Only a human
reading the code knows the invariant. And an assertfalse could be turned off, so the compiler would still
require the code to have a bogus return. The throw enforces what you already know.
The compiler will not let you have an assert statement it believes to be unreachable, just like it won't let
you have any other unreachable statement. When the compiler can determine that a line is unreachable, not
only do you need no assert, you may not put one there.
12.10. Turning Assertions On and Off
By default, assertion evaluation is turned off. You can turn on all assertion evaluation in a virtual machine, or
on a package, class, or class loader basis. Because they can be on or off, you must be careful to avoid side
effects that affect non-assertion code.
You control assertion evaluation either by passing command-line options to the virtual machinedescribed
shortlyor by using methods provided by the class loadersee "Controlling Assertions at Runtime" on page 444.