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)

Example of assertion with no expression

Example os assertion including an expression