Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

IllegalArgumentException

Signals that a method received an invalid argument.

Available since: Java 1.0

Syntax

public class IllegalArgumentException extends RuntimeException

Examples

Checking arguments at the start of a method:

double discount(double price, int percent) {
    if (percent < 0 || percent > 100) {
        throw new IllegalArgumentException("percent must be 0..100, got " + percent);
    }
    return price * (100 - percent) / 100;
}
 
void main() {
    IO.println(discount(200, 15));
    try {
        discount(200, 150);
    } catch (IllegalArgumentException e) {
        IO.println(e.getMessage());
    }
}

Output:

170.0
percent must be 0..100, got 150

A check in a record's compact constructor:

record Age(int value) {
    Age {
        if (value < 0) throw new IllegalArgumentException("negative age: " + value);
    }
}
 
void main() {
    IO.println(new Age(30));
    try {
        new Age(-1);
    } catch (IllegalArgumentException e) {
        IO.println(e);
    }
}

Output:

Age[value=30]
java.lang.IllegalArgumentException: negative age: -1

Notes

The most common exception for validating input: throw it as soon as an argument turns out wrong, with a clear message. For null arguments the convention is NullPointerException via Objects.requireNonNull().

See also

Related recipes

In the tutorial

  • Custom exceptions — How to create your own exception class in Java — extending Exception or RuntimeException, the message, the cause and extra fields.

Thanks for reading!

Donate to the site — we work hard for you.