CKTIS / Java
IllegalArgumentException — invalid argument
IllegalArgumentException signals that a method received an illegal or inappropriate argument. It is an unchecked exception: the compiler does not require callers to catch it or declare it with throws.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
throw new IllegalArgumentException("message");java.lang.IllegalArgumentException means that a supplied argument violates a method's requirements, such as a number outside an allowed range. In contrast, IllegalStateException signals that an operation was invoked in an inappropriate state or at an inappropriate time.
IllegalArgumentException extends RuntimeException, making it an unchecked exception. You do not have to catch it or include it in a throws declaration. This does not mean that the violated method contract can be ignored.
Typical syntax is throw new IllegalArgumentException("message");. The constructor accepting a String sets the message retrieved through getMessage(). Prefer checking arguments before performing side effects and describing the violated requirement in the message. Catch the exception where the problem can be handled meaningfully rather than hiding it.
In the example, requirePercentage accepts values from 0 through 100, inclusive. It returns its argument for 75 and explicitly throws an exception for 101. The catch block prints the message only for demonstration. The documentation scope is Java SE 21; the production runtime version has not been attested.
Examples
public class Main {
static int requirePercentage(int value) {
if (value < 0 || value > 100) {
throw new IllegalArgumentException("value must be between 0 and 100");
}
return value;
}
public static void main(String[] args) {
System.out.println(requirePercentage(75));
try {
requirePercentage(101);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}Result
75 value must be between 0 and 100
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.