assert

  • No libraries needed to be imported
  • They are disabled by default in java
  • To enable, you need -ea or -enableassertions at runtime in java command line
  • Hence they can be used in development
  • Syntax:
Connection conn = getConnection();
 
// expression1: boolean, expression2: Object/String/int/long/...
assert expression1 : expression2;
 
// without message
assert conn != null;
 
// with message
assert conn != null : "Connection is null";
  • Throws AssertionError if condition fails
    • extends Error < Throwable
  • AssertionError is same error thrown from usual assertion libraries
  • expression2 will be used as new AssertionException(expression2) and thrown

Best Practices

  • Assertions are great for places in the code that will never be executed, such as:
    • the default case of a switch statement
    • after a loop that never finishes
  • Do not test arguments of public methods
    • Use some other runtime exception like IllegalArgumentException
  • Don’t call methods in assert expression
    • save result and assert it