Java Reference
In-Depth Information
12.8. Assertions
An
assertion
is used to check an
invariant,
a condition that should always
be true. If the assertion is found to be false then an exception is thrown.
If your code assumes that something is true, adding an assertion to test
it gives you a way to catch mistakes before they cause odd effects. For
example, in a linked list the last element in the list usually has a
null
ref-
erence to the next element:
public void append(Object value) {
ListNode node = new ListNode(value);
if (tail != null)
tail.next = node;
tail = node;
assert tail.next == null;
}
When the
append
method has done its work, the
assert
double-checks that
the last node is properly formed. If it is not, then an
AssertionError
is
thrown.
By default, assertions are not evaluated. It is possible to turn assertion
evaluation on and off for packages, classes, and entire class loaders, as
you will soon see. When assertions are turned off, the assertions are not
evaluated at all. This means that you must be careful about side effects
that affect non-assertion code. For example, the following code is very
dangerous:
assert ++i < max;
When assertions are being evaluated, the value of
i
will be incremented
to the next value. But when someone turns off assertions the entire
expression will logically vanish from the code leaving
i
perpetually un-
changed. Don't ever do anything like this. Split it up: