🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, we will learn what is IllegalArgumentException in Java, its common causes, practical examples, solutions, and tips to avoid IllegalArgumentException.
What is IllegalArgumentException?
The IllegalArgumentException is a runtime exception thrown by the Java system (or by applications) to indicate that a method has received an argument that is invalid or inappropriate in context.
Common Causes
Passing Out-of-Range Values: For instance, passing a negative size to a method expecting a positive size.
Inappropriate Null Arguments: Passing null to a method that explicitly requires a non-null argument.
Incompatible Data Types: For instance, passing a string representing a date in the wrong format.
Out-of-bounds Values: Providing a value outside an expected range.
Practical Example
Let's dive into the IllegalArgumentException with a hands-on example:
public class Person {
private int age;
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
this.age = age;
}
public static void main(String[] args) {
Person person = new Person();
person.setAge(-5); // This will throw an IllegalArgumentException
}
}Output:
Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative.
at Person.setAge(Person.java:6)
at Person.main(Person.java:15)Solutions and Best Practices
1. Validation Before Processing
Always validate method arguments before processing. This ensures that if an IllegalArgumentException is to be thrown, it happens immediately, making it easier to identify and fix.
public void setTemperature(float temperature) {
if (temperature < -273.15) { // absolute zero in Celsius
throw new IllegalArgumentException("Temperature below absolute zero is not possible.");
}
// continue processing...
}2. Provide Detailed Error Messages
When throwing an IllegalArgumentException, always provide a detailed error message. This not only helps during debugging but also makes your code more understandable.
throw new IllegalArgumentException("Expected a non-negative value, but got: " + value);3. Leverage Java's Built-in Objects'
Methods Many built-in Java objects, like Objects.requireNonNull(), are designed to automatically throw IllegalArgumentException or related exceptions under certain conditions. Make use of these to simplify your validation process.
import java.util.Objects;
public void setName(String name) {
this.name = Objects.requireNonNull(name, "Name cannot be null");
}Tips to Avoid IllegalArgumentException
Unit Testing: Write unit tests that test boundary conditions and potential illegal arguments.
Consistent Validation: Be consistent in how you validate method arguments across your codebase.
Use Enums: For methods that accept only a limited set of values, consider using enums.
Related Exceptions Posts
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment