EMZETT.
Login

IllegalArgumentException

In short: IllegalArgumentException signals that a method received an argument that is not allowed, for example a negative size or an empty name.

In more detail: It is unchecked (extends RuntimeException) and one of the exceptions developers throw most often themselves. It tells the caller: the mistake is in your call, not in my method.

In detail

public void setHeight(int cm) {
    if (cm <= 0) {
        throw new IllegalArgumentException("Height must be positive: " + cm);
    }
    this.height = cm;
}
  • Fixing the cause: check the input before calling the method.
  • Message: put the wrong value into the message, it saves search time.
  • Related: IllegalStateException (object in the wrong state), NumberFormatException (subclass), NullPointerException for null.
  • Alternative: Objects.requireNonNull for null checks.

See also: throw and throws, Exception handling