Java IllegalArgumentException
Throw IllegalArgumentException when a caller supplies a value your method cannot accept. State the rule in the message so the caller can correct the input.
A simple example
IllegalArgumentException
- Start with A function needs a positive count
- Do this Supply 0
- Result Argument rejected
Syntax
throw new IllegalArgumentException("Guests must be at least 1");
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaValidate a table reservation
A booking form supplies a capacity or party size before a room can be assigned. Check the value at that boundary so the booking logic can work with a usable number of places.
public class Main {
static String booking(int guests) {
if (guests < 1) {
throw new IllegalArgumentException("Guests must be at least 1");
}
return "Seats reserved: " + guests;
}
public static void main(String[] args) throws Exception {
for (int guests : new int[]{3, 0}) {
try {
System.out.println(booking(guests));
} catch (IllegalArgumentException invalid) {
System.out.println(invalid.getMessage());
}
}
}
}
Seats reserved: 3 Guests must be at least 1
The booking method checks its own rule. A valid request reaches the return statement. Zero takes the exception path before a booking is created.
Reject a negative locker rental period
A student requests a locker for the coming term. A negative rental period in the form would move the return date backward, so the service rejects it before scheduling a return.
class Main {
public static void main(String[] args) throws Exception {
int weeks = -2;
try {
if (weeks <= 0) throw new IllegalArgumentException("Enter a positive rental period");
System.out.println("Booked for " + weeks + " weeks");
} catch (IllegalArgumentException invalid) {
System.out.println(invalid.getMessage());
}
}
}
Enter a positive rental period
The argument itself violates the rental contract, regardless of whether the locker is available.
Accept a team entry
A team asks for four places at the Saturday session. The workshop accepts a positive number of places. Reject zero before saving the reservation.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
int places=4;
if (places < 1) throw new IllegalArgumentException("places");
System.out.println("Reservation accepted");
} catch (IllegalArgumentException problem) {
System.out.println("Request a positive count");
}
}
}
Reservation accepted
What to watch for
This is an unchecked exception. A user interface can catch it at its input boundary and show a useful message.