Java Illegal Argument Exception(i.e IllegalArgumentException in java)
In Java, an IllegalArgumentException is a runtime exception that is thrown to indicate that a method has been passed an illegal or inappropriate argument. This exception is typically used to enforce valid method arguments and catch potential bugs early in the development process. Here are some examples of when and how to use IllegalArgumentException.
Basic Usage Example
Suppose you have a method that calculates the square root of a number. You might want to ensure that the number is not negative, as the square root of a negative number is not defined in the realm of real numbers.
public class MathUtils {
public static double calculateSquareRoot(double number) {
if (number < 0) {
throw new IllegalArgumentException("Number must be non-negative.");
}
return Math.sqrt(number);
}
public static void main(String[] args) {
try {
System.out.println(calculateSquareRoot(9)); // This will work fine
System.out.println(calculateSquareRoot(-1)); // This will throw an exception
} catch (IllegalArgumentException e) {
System.err.println("Caught an exception: " + e.getMessage());
}
}
}
Example with Multiple Arguments
You can also use IllegalArgumentException for methods with multiple parameters. Consider a method that sets the dimensions of a rectangle:
public class Rectangle {
private double width;
private double height;
public void setDimensions(double width, double height) {
if (width <= 0) {
throw new IllegalArgumentException("Width must be positive.");
}
if (height <= 0) {
throw new IllegalArgumentException("Height must be positive.");
}
this.width = width;
this.height = height;
}
public static void main(String[] args) {
Rectangle rectangle = new Rectangle();
try {
rectangle.setDimensions(5, 10); // Valid
rectangle.setDimensions(-5, 10); // Invalid, throws exception
} catch (IllegalArgumentException e) {
System.err.println("Caught an exception: " + e.getMessage());
}
}
}
Example with Collections
IllegalArgumentException is also useful for checking arguments related to collections, such as ensuring a list is not empty before performing operations on it.
import java.util.List;
public class ListUtils {
public static int getFirstElement(List<Integer> list) {
if (list == null) {
throw new IllegalArgumentException("List must not be null.");
}
if (list.isEmpty()) {
throw new IllegalArgumentException("List must not be empty.");
}
return list.get(0);
}
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3);
try {
System.out.println(getFirstElement(numbers)); // Prints 1
System.out.println(getFirstElement(List.of())); // Throws exception
} catch (IllegalArgumentException e) {
System.err.println("Caught an exception: " + e.getMessage());
}
}
}
When to Use IllegalArgumentException
Invalid Argument Values: If a method receives arguments that are not valid according to its logic or purpose.
Preconditions: When you want to enforce preconditions on method parameters to prevent incorrect usage.
User Input Validation: When processing user input, IllegalArgumentException can be used to reject bad data.
Handling IllegalArgumentException
IllegalArgumentException is an unchecked exception (a subclass of RuntimeException). It doesn't require mandatory handling with a try-catch block, but it's often a good practice to catch it where appropriate to provide meaningful error messages or alternative flows in your application.
try {
// Code that might throw IllegalArgumentException
} catch (IllegalArgumentException e) {
// Handle the exception, log it, or recover
}