By default, an assert
statement does nothing at all. However, if you launch your program with the VM option -enableassertions
(-ea
for short):
$ java -ea com.example.Main
Then this statement,
assert cond;
is equivalent to:
if (!cond)
throw new AssertionError();
For example, assert i == 0;
is equivalent to:
if (i != 0)
throw new AssertionError();
The Java Language Specification states the following:
14.10. The assert Statement
An assertion is an
assert
statement that contains a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, then the execution of the assertion causes an evaluation of the boolean expression and, if the expression evaluates tofalse
, an error is reported. If the assertion is disabled, execution of the assertion has no effect whatsoever.
Here, “enabled or disabled” is controlled with the -ea
switch. “An error is reported” means that an AssertionError
is thrown.
Assertions allow us to check the validity of a value. If an AssertionError
occurs, the code does not obey your assumptions.
A lesser-known feature of assert
is that you can append an error message. For example:
assert o != null : "o is null";
This error message is then passed to the AssertionError
constructor and printed along with the stack trace.
Free Resources