Java Reference
In-Depth Information
ments are useless for preventing bugs because the compiler ignores them.
Many languages address this problem by providing a language feature called asser-
helps the developer diagnose the failure's cause.
assertions via the javac compiler tool's command-line arguments.
Declaring Assertions
An assertion isastatementthatletsyouexpressanassumptionofprogramcorrectness
the ext statement. Otherwise, an error that identifies the cause of failure is thrown.
There are two forms of the assertion statement, each of which begins with reserved
word assert :
assert expression1 ;
assert expression1 : expression2 ;
In both forms of this statement, expression1 is the Boolean expression. In the
secondform, expression2 isanyexpressionthatreturnsavalue.Itcannotbeacall
to a method whose return type is void .
When expression1 evaluates to false, this statement instantiates the Asser-
tionError class. The first statement form calls this class's noargument constructor,
which does not associate a message identifying failure details with the Asser-
tionError instance.
The second form calls an AssertionError constructor whose type matches the
type of expression2 's value. This value is passed to the constructor and its string
representation is used as the error's detail message.
trace. In many situations, this information is sufficient for identifying what led to the
failure, and the first form of the assertion statement should be used.
Listing 3-31 demonstrates the first form of the assertion statement.
Search WWH ::

Custom Search