Java IllegalArgumentException
Example
Pass a value that is not allowed to a method, and catch the exception:
public class Main {
static void checkAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
System.out.println("Age: " + age);
}
public static void main(String[] args) {
try {
checkAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Error: the age cannot be negative.");
}
}
}
Definition and Usage
An IllegalArgumentException happens when a method gets an argument (a value that you pass to the method) that it does not accept, for example a negative number where only positive numbers make sense.
Many Java methods throw it, and you can throw it in your own methods to stop wrong values, like in the example.
Related Pages
Java Exceptions (try...catch) Tutorial
❮ Errors & Exceptions