Introduction
IllegalArgumentException
in Java is a runtime exception that occurs when a method receives an argument that is not valid. It helps ensure that methods are used with proper inputs.
Table of Contents
- What is
IllegalArgumentException
? - Common Causes
- Handling
IllegalArgumentException
- Examples of
IllegalArgumentException
- Conclusion
1. What is IllegalArgumentException?
IllegalArgumentException
is thrown to indicate that a method has been passed an inappropriate or invalid argument. It signals that the method’s contract has been violated.
2. Common Causes
- Passing
null
to methods that do not acceptnull
. - Providing arguments out of the acceptable range.
- Passing incompatible types.
3. Handling IllegalArgumentException
To handle IllegalArgumentException
:
- Use input validation before method calls.
- Implement try-catch blocks where necessary.
- Document method requirements clearly.
4. Examples of IllegalArgumentException
Example 1: Validating Method Arguments
This example demonstrates how to validate arguments to prevent IllegalArgumentException
.
public class ArgumentValidationExample { public static int divide(int a, int b) { if (b == 0) { throw new IllegalArgumentException("Divisor cannot be zero."); } return a / b; } public static void main(String[] args) { try { System.out.println("Result: " + divide(10, 2)); System.out.println("Result: " + divide(10, 0)); // Throws IllegalArgumentException } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Result: 5 Error: Divisor cannot be zero.
Example 2: Handling IllegalArgumentException
Here, we handle IllegalArgumentException
when an invalid argument is passed.
public class InvalidArgumentExample { public static void setAge(int age) { if (age < 0 || age > 150) { throw new IllegalArgumentException("Age must be between 0 and 150."); } System.out.println("Age set to: " + age); } public static void main(String[] args) { try { setAge(25); setAge(-5); // Throws IllegalArgumentException } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } } }
Output:
Age set to: 25 Error: Age must be between 0 and 150.
Conclusion
IllegalArgumentException
in Java is crucial for maintaining method integrity by ensuring that arguments passed to methods are valid. By properly validating inputs and handling exceptions, you can prevent errors and ensure that methods function correctly.