Exceptions, Assertions & Logging

Assertions

assert documents and checks internal invariants during development — zero cost in production because assertions are disabled by default and compile to nothing unless -ea is passed.
  • Syntax: assert condition; or assert condition : detailMessage;
  • Disabled by default; enable with java -ea (or -ea:com.mycompany...)
  • For internal invariants and unreachable states — never for public-API argument checking
  • A failed assert throws AssertionError — it should mean "impossible happened"
  • Never put side effects in an assertion
Internal invariants
private double normalize(double angle) {
    double result = angle % (2 * Math.PI);
    if (result < 0) result += 2 * Math.PI;
    assert result >= 0 && result < 2 * Math.PI : "normalize broke: " + result;
    return result;
}

switch (phase) {
    case SOLID -> melt();
    case LIQUID -> boil();
    default -> throw new AssertionError("unknown phase: " + phase);  // unreachable
}

The division of labor: public method preconditions are enforced with real exceptions (IllegalArgumentException, Objects.requireNonNull) because they guard against other people's bugs and must fire in production. Private helpers may assert their preconditions — the calling code is yours, and the checks document assumptions for free.

Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 7.4 — Using Assertions
  • Effective Java (3rd ed.)Item 49 (parameter checking contrast)