IllegalArgumentException: Validating Method Parameters
What you'll learn: When and how to throw IllegalArgumentException to enforce your method's preconditions.
What Is IllegalArgumentException?
IllegalArgumentException is an unchecked exception (a subclass of RuntimeException) that you throw when a method receives an argument that is technically the correct type but logically invalid for that method's purpose. Think of it as a bouncer at a club: the person has an ID (correct type), but they're not old enough (invalid value).
When to Throw It
You should throw IllegalArgumentException when:
- A numeric parameter is outside an acceptable range (e.g., negative age)
- A string parameter is empty when it shouldn't be
- An object reference is non-null but violates business rules
- Enum values are unexpected or inappropriate for the context
This is different from NullPointerException (which signals null when non-null is required) or IndexOutOfBoundsException (which signals invalid index access).
Example: Validating Parameters
public class BankAccount {
private double balance;
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Withdrawal amount must be positive");
}
if (amount > balance) {
throw new IllegalArgumentException("Insufficient funds");
}
balance -= amount;
}
}
Here, the amount parameter is a valid double, but certain values don't make sense for a withdrawal operation.
Why Validate Early
Throwing IllegalArgumentException at the method's entry point prevents your code from proceeding with bad data, making bugs easier to diagnose. It's defensive programming: catch logical errors immediately rather than letting them cause subtle problems later.
Key Takeaway: Throw IllegalArgumentException when method arguments are the right type but violate logical preconditions—it's your method's way of saying "I can't work with these values."