CIS 160 - Assertions

Objective

  • Use Java assertions

Assertion notes

  • Assertions are used to stop a program and display an error message
  • Assertions should be used to catch logic problems in programs that are unexpected
  • Assertions should not be used for normal data validation, especially not user input
  • The assertion mechanism has a lot of overhead so assertions are not normally enabled
  • Programs get compiled with assertions, but need to have the -enableassertions or -ea option to the java program to work
  • One syntax form is: assert condition; // error displayed if condition false
  • Another syntax form is: assert condition:expression; // error and expression displayed if condition false
  • You can enable system assertions (not demonstrated here)
  • You can enable assertions for some classes and disable them for others (not demonstrated here)

Assertion with no expression

public class Assert1 { public static void main(String[] args) { display("This is a test of the assertion mechanism"); display(null); } private static void display(String msg) { assert msg != null; System.out.println(msg); } } /* Sample output: C:\>javac Assert1.java C:\>java Assert1 This is a test of the assertion mechanism null C:\>java -ea Assert1 This is a test of the assertion mechanism Exception in thread "main" java.lang.AssertionError at Assert1.display(Assert1.java:8) at Assert1.main(Assert1.java:4) C:\>java -enableassertions Assert1 This is a test of the assertion mechanism Exception in thread "main" java.lang.AssertionError at Assert1.display(Assert1.java:8) at Assert1.main(Assert1.java:4) */

Assertion including an expression

public class Assert2 { public static void main(String[] args) { display("This is a test of the assertion mechanism"); display(null); } private static void display(String msg) { assert msg != null : "Message to display(String) was null"; System.out.println(msg); } } /* Sample output: C:\>javac Assert2.java C:\>java Assert2 This is a test of the assertion mechanism null C:\>java -ea Assert2 This is a test of the assertion mechanism Exception in thread "main" java.lang.AssertionError: Message to display(String) was null at Assert2.display(Assert2.java:8) at Assert2.main(Assert2.java:4) C:\>java -enableassertions Assert2 This is a test of the assertion mechanism Exception in thread "main" java.lang.AssertionError: Message to display(String) was null at Assert2.display(Assert2.java:8) at Assert2.main(Assert2.java:4) */

Resource