Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to validate method arguments

Short answer

Check arguments at the start of the method and throw an IllegalArgumentException with a clear message:

double discount(double price, int percent) {
    if (percent < 0 || percent > 100) {
        throw new IllegalArgumentException("percent must be 0..100, got " + percent);
    }
    return price * percent / 100;
}
 
void main() {
    IO.println(discount(80, 25));
    IO.println(discount(80, 150));
}

Output:

20.0
Exception in thread "main" java.lang.IllegalArgumentException: percent must be 0..100, got 150

null

Objects.requireNonNull() checks the reference and returns it — you can combine the check with an assignment:

class Greeter {
    private final String name;
 
    Greeter(String name) {
        this.name = Objects.requireNonNull(name, "name");
    }
}
 
void main() {
    new Greeter("Anna");
    IO.println("ok");
    new Greeter(null);
}

Output:

ok
Exception in thread "main" java.lang.NullPointerException: name

Indexes

Objects.checkIndex() checks that an index is within [0, length):

void main() {
    int[] slots = new int[3];
    IO.println(Objects.checkIndex(2, slots.length));
    Objects.checkIndex(3, slots.length);
}

Output:

2
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3

Object state

If the problem is not the argument but the object's state, use IllegalStateException:

class Order {
    boolean paid;
 
    void ship() {
        if (!paid) {
            throw new IllegalStateException("order is not paid yet");
        }
    }
}
 
void main() {
    new Order().ship();
}

Output:

Exception in thread "main" java.lang.IllegalStateException: order is not paid yet

Common mistake

Returning "special" values like -1 or null for invalid arguments. The caller easily forgets to check them, and the error surfaces later somewhere else. An exception stops the program immediately, right where the error happened.

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.