Java Reference
In-Depth Information
For example, we could have written the assertion in the last code fragment as:
assert false : "daysInMonth has the value " + daysInMonth;
Now if the program asserts, the output will include information about the value of daysInMonth .
Let's see how it works in practice.
Try It Out - A Working Assertion
Here's some code that is guaranteed to assert - if you compile and execute it right:
public class TryAssertions {
public static void main(String args[]) {
int daysInMonth = 32;
if(daysInMonth == 30) {
System.out.println("Month is April, June, September, or November");
} else if(daysInMonth == 31) {
System.out.println(
"Month is January, March, May, July, August, October, or December.");
} else if(daysInMonth == 28 || daysInMonth == 29) {
System.out.println("Month is February.");
} else {
assert false;
}
}
}
Don't forget, you must compile this with the -source 1.4 option specified:
javac -source 1.4 TryAssertions.java
You must also execute it with the command:
java -enableassertions TryAssertions
You should then get the output:
java.lang.AssertionError
at TryAssertions.main(TryAssertions.java:1)
Exception in thread "main"
How It Works
Since we have set daysInMonth to an invalid value, the assertion statement is executed, and that
results in the error message. You could try the other form of the assertion:
Search WWH ::




Custom Search