BackendBench
Coffee

Home โ€บ Java exceptions โ€บ IllegalArgumentException

Unchecked exception ยท java.lang

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.PURPLE

Extends 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

How to fix it

  1. Read the message: well-written code states which argument was wrong and why.
  2. Validate input at the edge and return a proper error to the caller instead of letting the exception escape.
  3. For enums, write a lookup that returns an Optional, or catch the exception where the text enters.
  4. Throw IllegalArgumentException in your own methods with a message that includes the bad value.

Broken and fixed

fails
Color c = Color.valueOf(userInput); // "No enum constant Color.PURPLE"
works
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.

Related exceptions

More tools you might need