Java Reference
In-Depth Information
if (x % 2 == 0) {
} else { // { x % 2 == 1 }
You can now write this code this way:
if (x%2==0) {
} else {
assert x%2==1: "x = " + x ;
If, for some reason, the assertion of the assert statement (the boolean-expres-
sion ) should ever be false at that point during execution, the program will abort
with a message, and you will know that there is a problem.
The assertion statement is intended to be used for internal checking of a pro-
gram while a program is being developed. You are encouraged to leave assertions
in a program when it is completed just in case all bugs have not been found and
corrected. But assertions are not intended to be used to alert a user of a program
to errors they have made. For such problems, the normal error-handling mecha-
nisms should be used.
For example, suppose we are writing a private method, called only by our
own methods, that has a precondition 0<n<100 . We can use an assert statement
to check the precondition, as shown here:
/** = English equivalent of n, for 0 <n<100 */
private static String anglicize( int n) {
assert 0<n&&n<100: "n is " + n;
However, if the method is public and you have no control over the places
from which it is called, it is better to throw the appropriate exception:
/** = English equivalent of n, for 0 < n < 100
Throw an IllegalArgumentException if n out of range */
private static String anglicize( int n) {
if (0 >= n || n >= 100)
{ throw new IllegalArgumentException("n is: " + n); }
Throw statements are discussed in Chap. 10 on Exception handling . Do not
be concerned if you do not know about exceptions; if you want to test a parame-
ter's precondition, just use the throw statement shown above, putting as the argu-
ment of the constructor of IllegalArgumentException a string that explains
the problem.
Generally, you can use the assert statement to test loop invariants, postcon-
ditions of methods, and other assertions that you previously wrote as comments.
Search WWH ::

Custom Search