Java Reference
In-Depth Information
Assert statements may or may not be executed, so the compiler will not
always consider them reachable. A variable that is initialized only in an
assert statement will be considered potentially uninitialized because if
asserts are disabled it will be uninitialized. This will be true even if all
uses of the variable are in other assert statements.
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 unexpec-
tedly 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 as-
sert with a throw :
throw new AssertionError("replace: can't find " + val);
 
Search WWH ::




Custom Search