Assertions in Java

assert Expression1 : Expression2;
  • Expression1 is asserted to be true; otherwise AssertionError (that shouldn’t be handled) is thrown
  • Expression2 allows to produce some additional information
  • Expression2 MUST result in a value – it generates a String message
  • allow testing during the development and debugging
  • are disabled at runtime by default
  • can be enabled using -ea or -enableassertions flags and selectively disabled using -da or -disableassertions flags, e.g:
    • java -ea -da:MyClass NotMyClass – enable in general but disable for MyClass
    • java -ea -da:net.dobrzanski.util... MyClass – enable in general but disable for all classes from net.dobrzanski.util package and any of its subpackages
    • java -ea -dsa MyClass, which is shorter version of java -enableassertions -disablesystemassertions MyClass – enable in general but disable in system classes
  • DO NOT USE to validate arguments to public methods
  • DO NOT USE to validate command line arguments
  • USE to validate arguments to private methods
  • USE to validate that particular code block will never be reached (use assert false; in that case)
  • assert can be used as a key word (as of Java 1.4) or as an identifier, but never both at the same time
  • Shorter version:

private void doSth() {
   ...
   assert (a < b);
   // in there, a is lower than b
   ...
}

Longer version:

private void doSth() {
   ...
   assert (a < b) : "a=" + a + ", b=" + b;
   // in there, a is lower than b
   ...
}
Previous Post
Next Post