Java Reference
In-Depth Information
Maintaining Program Correctness with Assertions
Problem
You want to leave tests in your code but not have runtime checking overhead until you need
it.
Solution
Use the Java assertion mechanism.
Discussion
The Java language assert keyword takes two arguments separated by a colon (by analogy
with the conditional operator): an expression that is asserted by the developer to be true, and
a message to be included in the exception that is thrown if the expression is false. Normally,
assertions are meant to be left in place (unlike quick-and-dirty print statements, which are of-
ten put in during one test and then removed). To reduce runtime overhead, assertion checking
is not enabled by default; it must be enabled explicitly with the -enableassertions (or -
ea ) command-line flag. Here is a simple demo program that shows the use of the assertion
mechanism:
testing/AssertDemo.java
public
public class
class AssertDemo
AssertDemo {
public
public static
static void
void main ( String [] args ) {
int
int i = 4 ;
iif ( args . length == 1 ) {
i = Integer . parseInt ( args [ 0 ]);
}
assert
assert i > 0 : "i is non-positive" ;
System . out . println ( "Hello after an assertion" );
}
}
$ javac -d . testing/AssertDemo.java
$ java testing.AssertDemo -1
Hello after an assertion
$ java -ea testing.AssertDemo -1
Exception in thread "main" java.lang.AssertionError: i is non-positive
Search WWH ::




Custom Search