IllegalArgumentException
Signals that a method received an invalid argument.
Available since: Java 1.0
Syntax
public class IllegalArgumentException extends RuntimeExceptionExamples
Checking arguments at the start of a method:
double discount(double price, int percent) {
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException("percent must be 0..100, got " + percent);
}
return price * (100 - percent) / 100;
}
void main() {
IO.println(discount(200, 15));
try {
discount(200, 150);
} catch (IllegalArgumentException e) {
IO.println(e.getMessage());
}
}Output:
170.0
percent must be 0..100, got 150A check in a record's compact constructor:
record Age(int value) {
Age {
if (value < 0) throw new IllegalArgumentException("negative age: " + value);
}
}
void main() {
IO.println(new Age(30));
try {
new Age(-1);
} catch (IllegalArgumentException e) {
IO.println(e);
}
}Output:
Age[value=30]
java.lang.IllegalArgumentException: negative age: -1Notes
The most common exception for validating input: throw it as soon as an argument turns out wrong, with a clear message. For null arguments the convention is NullPointerException via Objects.requireNonNull().
See also
- IllegalStateException — Signals that a method was called at the wrong time — the object is in the wrong state.
- NumberFormatException — Thrown when a string cannot be converted to a number.
- RuntimeException — The base class of unchecked exceptions — bugs in program logic.
Related recipes
In the tutorial
- Custom exceptions — How to create your own exception class in Java — extending Exception or RuntimeException, the message, the cause and extra fields.