Home โบ Java exceptions โบ IllegalArgumentException
IllegalArgumentException: causes and fixes
A method received an argument that is not acceptable, as decided by the method itself.
What it looks like
java.lang.IllegalArgumentException: No enum constant Color.PURPLEExtends RuntimeException in java.lang.
What it means
IllegalArgumentException is the standard way for a method to reject an argument whose value is wrong, as opposed to null (NullPointerException) or an object in the wrong state (IllegalStateException). The JDK throws it from many places, such as new ArrayList(-1), Enum.valueOf with an unknown name and Thread.sleep(-1), and so should your own validation code.
Common causes
Enum.valueOf("RED")when the enum has no such constant: "No enum constant Color.RED".- A negative size, timeout or percentage passed to a constructor or method.
- A malformed value such as an invalid URI, UUID, or time zone id.
- A Spring assertion (
Assert.notNull,Assert.hasText) that failed during configuration.
How to fix it
- Read the message: well-written code states which argument was wrong and why.
- Validate input at the edge and return a proper error to the caller instead of letting the exception escape.
- For enums, write a lookup that returns an Optional, or catch the exception where the text enters.
- Throw IllegalArgumentException in your own methods with a message that includes the bad value.
Broken and fixed
Color c = Color.valueOf(userInput); // "No enum constant Color.PURPLE"Optional<Color> c = Arrays.stream(Color.values())
.filter(x -> x.name().equalsIgnoreCase(userInput))
.findFirst();๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
Spring turns an IllegalArgumentException from a controller into a 500 unless you map it. Handle it in a @ControllerAdvice and return a 400 with a clear message.
Debug it faster
Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.
Frequently asked questions
Is IllegalArgumentException a checked or unchecked exception?
IllegalArgumentException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.
Which package is IllegalArgumentException in?
It lives in java.lang, so the import is import java.lang.IllegalArgumentException; (java.lang needs no import).
What is the first thing to check when I see IllegalArgumentException?
Read the message and the first stack trace line in your own code. The usual causes are: Enum.valueOf("RED") when the enum has no such constant: "No enum constant Color.RED"; and A negative size, timeout or percentage passed to a constructor or method.