The Assert Statement

Introduced with Java 1.4, the assert statement helps to debug code and also troubleshoot applications after they have been deployed. You write an assert statement stating some very important condition that you believe will always be true at this point in your program. If the condition is not true, the assertion throws an Error (a Throwable thing that is not intended to be caught). You can do that already in Java. The part that is new is that assertion statements let you choose at run-time whether the assertion checking is on or off.

Two key steps in using assert

There are two key pieces to using asserts.

  • First, you sprinkle assert statements at a few critical places in your program. For example, after calculating a checksum, you could assert that the calculated value equals the stored checksum. You only use assert statements for fatal errors—something has gone so wrong that the only thing to do is stop before more data disappears or whatever.

  • The second half of assert statements is that you control whether the assert statements are in effect, or not, at run-time. There is a command line option to the JVM that enables or disables whether the assertions are executed, and this can be applied to individual packages and even classes.

The usual scenario is that you keep the assert statements on during debugging and testing. After testing, when you are confident that the application works correctly, you no longer need to do all that checking. So you disable the assert statements, but leave them compiled in the source code. If the application later hits a problem, you can enable asserts and rerun the failure case to see if any assertions are untrue. This can be done in the field or over telephone support.

An assert statement looks like either of these alternatives:

assert booleanExpression;

assert booleanExpression : Expression2;

If the boolean is not true, a java.lang.AssertionError is thrown. The second form of the statement allows you to write an expression that will be passed to the constructor of the AssertionError. The expression is supposed to resolve to a message about what went wrong. You should just pass a String. An expression of other types (such as int) is allowed to accommodate those crazies who want to number their error messages or label them with a character instead of using self-identifying strings.

Complete example of assert

Here's a complete example of the use, compilation, and run of a program with assert.

public class asst {
    public static void main(String[] args) {

        int a = Integer.parseInt(args[0]);
        System.out.println("a = "+a);

        assert a>=0 : "argument too negative";

        // if a OK, go on with program
    }
}

That assert statement is equivalent to this line of code:

if (a<0) throw new java.lang.AssertionError("argument too negative");

except that you have the additional ability to configure whether such statements should be executed or not.

When using assert statements, Sun's JDK 1.4 compiler needs the -source 1.4 command line option. That option is not needed when using Sun's Java 5 compiler. This is to avoid code breakage with people who have created their own version of assertions in the past and used the identifier "assert". Compile as follows:

javac -source 1.4 asst.java

Even after you have compiled them in, by default assertions are disabled at run-time. Here is a regular program execution where no error occurs, even though we provided a command line argument that triggers the problem.

java asst -3

To turn on the assertion checking for a particular run, use the “-ea” (enable assertions) option to java:

java -ea asst -3
Exception in thread "main" java.lang.AssertionError: argument too negative at asst.main(asst.java:7)

There is also a syntax for enabling just one package tree or a class, but you might as well do everything. A separate switch is provided to enable asserts in the system classes (i.e., to set the assertion status for java.* packages to true).

java  -esa  MyProgram

If you ever get a run-time error in the JVM, such as a core dump, try running with the “-esa” option and including the output in your bug report to Sun. You can search and file bug reports on the JDK at the Java Developer Connection site developer.java.sun.com.

Points to watch with assert

There are a couple of caveats with assertion statements. First, you must test your code both ways, with assertions enabled and disabled.

Second, you must avoid side effects in the assertion expression. Otherwise, program behavior would be different depending on whether you run with assertions on or off. A “side effect” is a change to the value of some variable, as part of evaluating the expression, e.g.,

boolean noMoreData = true;

boolean checkingMethod() {
    noMoreData = false;
    return noMoreData;
}
assert checkingMethod();

Now, variable noMoreData has a different value from this point in the program, depending on whether assertions are on or off! Avoid this.

Finally, assertions are supposed to be unrecoverable errors, so do not try to repair the problem and continue. That is what exceptions are for. Assert statements provide the ability to check for significant errors and to make the checking configurable at run-time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.197.213