Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions

  




 

 

Thinking in Java
Prev Contents / Index Next

Assertion syntax

Since you can simulate the effect of assertions using other programming constructs, it can be argued that the whole point of adding assertions to Java is that they are easy to write. Assertion statements come in two forms:

assert boolean-expression;
assert boolean-expression: information-expression;


Both of these statements say “I assert that the boolean-expression will produce a true value.” If this is not the case, the assertion will produce an AssertionError exception. This is a Throwable subclass, and as such doesn’t require an exception specification.

Unfortunately, the first form of assertion does not produce any information containing the boolean-expression in the exception produced by a failed assertion (in contrast with most other languages’ assertion mechanisms). Here’s an example showing the use of the first form:

//: c15:Assert1.java
// Non-informative style of assert
// Compile with: javac -source 1.4 Assert1.java
// {JVMArgs: -ea} // Must run with -ea
// {ThrowsException}

public class Assert1 {
  public static void main(String[] args) {
    assert false;
  }
} ///:~


Assertions are turned off in JDK 1.4 by default (this is annoying, but the designers managed to convince themselves it was a good idea). To prevent compile-time errors, you must compile with the flag:

-source 1.4


If you don’t use this flag, you’ll get a chatty message saying that assert is a keyword in JDK 1.4 and cannot be used as an identifier anymore.

If you just run the program the way you normally do, without any special assertion flags, nothing will happen. You must enable assertions when you run the program. The easiest way to do this is with the -ea flag, but you can also spell it out: -enableassertions. This will run the program and execute any assertion statements, so you’ll get:

Exception in thread "main" java.lang.AssertionError
        at Assert1.main(Assert1.java:8)


You can see that the output doesn’t contain much in the way of useful information. On the other hand, if you use the information-expression, you’ll produce a helpful message when the assertion fails.

To use the second form, you provide an information-expression that will be displayed as part of the exception stack trace. This information-expression can produce any data type at all. However, the most useful information-expression will typically be a string with text that is useful to the programmer. Here’s an example:

//: c15:Assert2.java
// Assert with an informative message
// {JVMArgs: -ea}
// {ThrowsException}

public class Assert2 {
  public static void main(String[] args) {
    assert false: "Here's a message saying what happened";
  }
} ///:~


Now the output is:

Exception in thread "main" java.lang.AssertionError: Here's a message saying what happened
        at Assert2.main(Assert2.java:6)


Although what you see here is just a simple String object, the information-expression can produce any kind of object, so you will typically construct a more complex string containing, for example, the value(s) of objects that were involved with the failed assertion.

Because the only way to see useful information from a failed assertion is to use the information-expression, that is the form that is always used in this book, and the first form will be considered to be a poor choice.

You can also decide to turn assertions on and off based on class name or package name (that is, you can enable or disable assertions in an entire package). You can find the details in the JDK 1.4 documentation on assertions. This can be useful if you have a large project instrumented with assertions and you want to turn some of them off. However, logging or debugging (both described later in this chapter) are probably better tools for capturing that kind of information. This book will just turn on all assertions when necessary, so we will ignore the fine-grained control of assertions.

There’s one other way you can control assertions: programmatically, by hooking into the ClassLoader object. JDK 1.4 added several new methods to ClassLoader that allow the dynamic enabling and disabling of assertions, including setDefaultAssertionStatus( ), which sets the assertion status for all the classes loaded afterward. So you might think you could almost silently turn on all assertions like this:

//: c15:LoaderAssertions.java
// Using the class loader to enable assertions
// Compile with: javac -source 1.4 LoaderAssertions.java
// {ThrowsException}

public class LoaderAssertions {
  public static void main(String[] args) {
    ClassLoader.getSystemClassLoader()
      .setDefaultAssertionStatus(true);
    new Loaded().go();
  }
}

class Loaded {
  public void go() {
    assert false: "Loaded.go()";
  }
} ///:~


Although this does eliminate the need to use the -ea flag on the command line when the Java program is run, it’s not a complete solution because you must still compile everything with the -source 1.4 flag. It may be just as straightforward to enable assertions using command-line arguments; when delivering a standalone product, you probably have to set up an execution script for the user to start the program anyway, in order to configure other startup parameters.

It does make sense, however, to decide that you want to require assertions to be enabled when the program is run. You can accomplish this with the following static clause, placed in the main class of your system:

static {
  boolean assertionsEnabled = false;
  // Note intentional side effect of assignment:
  assert assertionsEnabled = true;
  if (!assertionsEnabled)
    throw new RuntimeException("Assertions disabled");
}


If assertions are enabled, then the assert statement will be executed and assertionsEnabled will be set to true. The assertion will never fail, because the return value of the assignment is the assigned value. If assertions are not enabled, the assert statement will not be executed and assertionsEnabled will remain false, resulting in the exception.
Thinking in Java
Prev Contents / Index Next


 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire