Java Reference
In-Depth Information
2. A method can skip the check and work under the assumption that the
preconditions are fulfilled. If they aren't, then any data corruption (such as a
negative balance) or other failures are the caller's fault.
The first approach can be inefficient, particularly if the same check is carried out
many times by several methods. The second approach can be dangerous. The
assertion mechanism was invented to give you the best of both approaches.
An assertion is a condition that you believe to be true at all times in a particular
program location. An assertion check tests whether an assertion is true. Here is a
typical assertion check that tests a precondition:
An assertion is a logical condition in a program that you believe to be true.
public double deposit (double amount)
{
assert amount >= 0;
balance = balance + amount;
}
In this method, the programmer expects that the quantity amount can never be
negative. When the assertion is correct, no harm is done, and the program works in
the normal way. If, for some reason, the assertion fails, and assertion checking is
enabled, then the program terminates with an AssertionError .
However, if assertion checking is disabled, then the assertion is never checked, and
the program runs at full speed. By default, assertion checking is disabled when you
execute a program. To execute a program with assertion checking turned on, use this
command:
java -enableassertions MyProg
348
349
S YNTAX 8.1: Assertion
assert condition;
Example:
assert amount >= 0;
Search WWH ::




Custom Search