IllegalArgumentException is one of the most commonly encountered runtime exceptions in Java. It occurs when a method receives an argument that is valid in type but invalid in value. In other words, the parameter passed to a method does not satisfy the method’s expected conditions, even though the data type is correct.
For example, passing a negative age where only positive values are allowed or providing an invalid month number to a date-related method can result in an IllegalArgumentException.
This exception is widely used in the Java Standard Library, Spring Framework, Hibernate, and many third-party libraries to validate method parameters and provide meaningful error messages.
In this guide, you’ll learn what IllegalArgumentException is, why it occurs, common causes, practical examples, and the best ways to fix and prevent it.
What is IllegalArgumentException?
IllegalArgumentException is an unchecked exception that belongs to the java.lang package.
It is thrown to indicate that a method has received an illegal or inappropriate argument.
Example:
Exception in thread “main”
java.lang.IllegalArgumentException
Unlike compile-time errors, this exception occurs at runtime when the application executes the code.
Why Does IllegalArgumentException Occur?
An IllegalArgumentException occurs when:
- A method receives an invalid value.
- The parameter is outside the accepted range.
- A required condition is not met.
- The argument format is incorrect.
- The value violates business rules.
For example, a method that accepts ages between 1 and 120 should reject negative numbers or values greater than 120.
Common Causes of IllegalArgumentException
Some of the most common causes include:
- Passing negative numbers where only positive values are allowed.
- Providing an invalid index or position.
- Supplying an incorrect enum value.
- Invalid date or time values.
- Passing empty or blank Strings.
- Invalid collection sizes.
- Incorrect configuration values.
- Invalid ranges.
- Null values (in custom validation).
- Violating method preconditions.
Example 1: Negative Value
Incorrect code:
public class Main {
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
System.out.println(age);
}
public static void main(String[] args) {
setAge(-5);
}
}
Output:
java.lang.IllegalArgumentException:
Age cannot be negative.
The method expects a positive age, but a negative value was supplied.
Example 2: Invalid Range
public class Main {
static void setPercentage(int percentage) {
if (percentage 100) {
throw new IllegalArgumentException(
"Percentage must be between 0 and 100.");
}
System.out.println(percentage);
}
public static void main(String[] args) {
setPercentage(150);
}
}
The percentage exceeds the accepted range.
Example 3: Empty String
public class Main {
static void setName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException(
"Name cannot be empty.");
}
System.out.println(name);
}
public static void main(String[] args) {
setName("");
}
}
An empty name is considered an invalid argument.
How IllegalArgumentException Works
Suppose a method expects values between 1 and 12 for months.
public static void setMonth(int month) {
if (month 12) {
throw new IllegalArgumentException(
"Invalid month.");
}
}
Calling:
setMonth(15);
immediately throws an exception because 15 is outside the valid range.
Solution 1: Validate Input Before Calling Methods
Instead of passing unchecked values:
setAge(age);
Validate them first:
if (age >= 0) {
setAge(age);
} else {
System.out.println("Invalid age.");
}
Input validation reduces runtime exceptions.
Solution 2: Validate Parameters Inside Methods
Every public method should validate its own parameters.
Example:
public static void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Amount must be greater than zero.");
}
}
Never assume callers always provide valid arguments.
Solution 3: Handle the Exception
Although prevention is preferable, you can catch the exception.
try {
setAge(-10);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
Output:
This prevents the application from terminating unexpectedly.
Solution 4: Check for Null Values
Methods often expect non-null arguments.
Incorrect:
processName(null);
Correct:
if (name != null) {
processName(name);
}
Or validate inside the method:
if (name == null) {
throw new IllegalArgumentException(
"Name cannot be null.");
}
Solution 5: Validate String Content
Avoid accepting empty or whitespace-only Strings.
if (text == null || text.isBlank()) {
throw new IllegalArgumentException(
"Text cannot be blank.");
}
This is common in form validation and REST APIs.
Solution 6: Validate Numeric Ranges
Example:
if (salary < 0) {
throw new IllegalArgumentException(
"Salary cannot be negative.");
}
Always verify numeric ranges before processing data.
Solution 7: Use Meaningful Exception Messages
Instead of:
throw new IllegalArgumentException();
Use:
throw new IllegalArgumentException(
"Quantity must be greater than zero.");
Clear messages make debugging much easier.
Solution 8: Use Objects.requireNonNull()
Java provides a convenient utility method.
import java.util.Objects;
Objects.requireNonNull(name,
"Name cannot be null.");
This throws a NullPointerException with a descriptive message if the value is null, making it easier to identify the issue.
Solution 9: Validate Collections
Example:
if (list == null || list.isEmpty()) {
throw new IllegalArgumentException(
"List cannot be empty.");
}
This prevents methods from operating on invalid collections.
Solution 10: Validate Enum Values
Example:
public enum Status {
ACTIVE,
INACTIVE
}
Always verify user input before converting Strings to enums.
Incorrect:
Status.valueOf("Running");
This can throw an exception because “Running” is not a valid enum constant.
Validate the input before conversion or handle the exception appropriately.
Solution 11: Use Preconditions in Large Projects
Large applications often centralize validation.
Example:
if (price <= 0) {
throw new IllegalArgumentException(
"Price must be positive.");
}
Validating method preconditions improves code quality and makes errors easier to diagnose.
Solution 12: Document Accepted Arguments
Good documentation helps prevent misuse.
Example:
/**
* Sets employee age.
*
* @param age must be between 18 and 60
*/
Developers can immediately understand the method’s expectations.
Real-World Example
Incorrect implementation:
public class Main {
static void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Invalid withdrawal amount.");
}
System.out.println("Withdrawal successful.");
}
public static void main(String[] args) {
withdraw(-500);
}
}
Output:
java.lang.IllegalArgumentException:
Invalid withdrawal amount.
Correct implementation:
public class Main {
static void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Amount must be greater than zero.");
}
System.out.println("Withdrawal successful.");
}
public static void main(String[] args) {
try {
withdraw(500);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
Output:
Common Scenarios That Cause IllegalArgumentException
| Scenario | Solution |
|---|---|
| Negative numbers | Validate before processing |
| Invalid ranges | Check minimum and maximum values |
| Empty Strings | Use isBlank() or isEmpty() |
| Null values | Validate or use Objects.requireNonNull() |
| Invalid enum values | Verify before conversion |
| Business rule violations | Throw descriptive exceptions |
| Incorrect method arguments | Validate parameters at the beginning of methods |
Best Practices to Prevent IllegalArgumentException
Follow these recommendations:
- Validate all method parameters.
- Check numeric ranges before processing.
- Reject invalid input as early as possible.
- Provide meaningful exception messages.
- Validate Strings for null, empty, or blank values.
- Verify collections before accessing them.
- Use reusable validation methods where appropriate.
- Document expected parameter ranges in Javadoc.
- Handle user input carefully.
- Write unit tests for invalid argument scenarios.
Frequently Asked Questions (FAQs)
What is IllegalArgumentException in Java?
IllegalArgumentException is an unchecked runtime exception thrown when a method receives an argument that is inappropriate or outside the accepted range.
Is IllegalArgumentException a checked exception?
No. It extends RuntimeException, making it an unchecked exception. It does not need to be declared with the throws keyword.
When should I throw IllegalArgumentException?
You should throw IllegalArgumentException when a method receives:
- Invalid numeric values
- Empty or blank Strings
- Values outside the allowed range
- Invalid configuration values
- Arguments that violate business rules
What is the difference between IllegalArgumentException and NullPointerException?
- IllegalArgumentException is used when the argument value is invalid, even if its type is correct.
- NullPointerException occurs when your code attempts to use a null reference where an object is required.
For example, passing -5 to a method that expects a positive number is an IllegalArgumentException, while calling a method on a null object results in a NullPointerException.
Conclusion
IllegalArgumentException is one of the most useful runtime exceptions in Java because it helps developers detect invalid method arguments early in the execution process. It is commonly used to enforce input validation, business rules, and API contracts. By validating parameters, checking numeric ranges, handling null and empty values, providing meaningful exception messages, and documenting expected inputs, you can write safer, more maintainable, and user-friendly Java applications. Proper use of IllegalArgumentException not only improves code quality but also makes debugging and maintenance significantly easier.