Use exceptions rather than assertions for handling critical error conditions that need to be caught in production. Assertions should only be used for development-time invariant checking that should never occur in production code.

Bad:

assert bestAssignment != -1 : "Failed to assign vector to centroid";

Good:

if (bestAssignment == -1) {
    throw new IllegalStateException("Failed to assign vector to centroid");
}

Assertions are disabled by default in production environments, which means critical error conditions could be silently ignored. This can lead to data corruption or system instability. Instead:

  1. Use exceptions for error conditions that:
  2. Reserve assertions for:

When choosing between exceptions and assertions, ask “Should this error be caught and handled in production?” If yes, use an exception.