🎓 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
Introduction
In Kotlin, IllegalArgumentException is a standard exception that is thrown to indicate that a method has been passed an illegal or inappropriate argument. This exception is part of the Kotlin (and Java) standard library and is used to signal that an argument does not meet the requirements of the method.
Table of Contents
- What is
IllegalArgumentException? - Common Causes of
IllegalArgumentException - Handling
IllegalArgumentException - Examples of
IllegalArgumentException - Real-World Use Case
- Conclusion
1. What is IllegalArgumentException?
IllegalArgumentException is a subclass of RuntimeException and is used to indicate that a method has received an argument that is not valid. This can include arguments that are out of range, null when a non-null value is required, or otherwise inappropriate for the method's purpose.
Syntax
throw IllegalArgumentException("Exception message")
2. Common Causes of IllegalArgumentException
- Passing null values to methods that do not accept them.
- Passing out-of-range values to methods.
- Providing arguments that do not meet the method's requirements.
Example
fun validateAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
}
3. Handling IllegalArgumentException
You can handle IllegalArgumentException using a try-catch block to prevent your program from crashing.
Example
fun main() {
try {
validateAge(-1)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
}
fun validateAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
}
4. Examples of IllegalArgumentException
Example 1: Validating Input
This example demonstrates how to validate input and throw IllegalArgumentException if the input is invalid.
fun main() {
try {
validateAge(-1)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
}
fun validateAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
}
Output:
Caught an illegal argument exception: Age cannot be negative
Explanation:
This example catches and handles an IllegalArgumentException caused by an invalid age input.
Example 2: Validating Non-Null Arguments
This example demonstrates how to validate that an argument is not null.
fun main() {
try {
printName(null)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
}
fun printName(name: String?) {
requireNotNull(name) { "Name cannot be null" }
println("Name: $name")
}
Output:
Caught an illegal argument exception: Name cannot be null
Explanation:
This example uses the requireNotNull function to check that the name is not null and throws an IllegalArgumentException if it is.
Example 3: Checking Argument Range
This example demonstrates how to validate that an argument is within a specific range.
fun main() {
try {
setTemperature(150)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
}
fun setTemperature(temperature: Int) {
require(temperature in -50..100) { "Temperature must be between -50 and 100 degrees" }
println("Temperature set to $temperature")
}
Output:
Caught an illegal argument exception: Temperature must be between -50 and 100 degrees
Explanation:
This example uses the require function to check that the temperature is within the valid range and throws an IllegalArgumentException if it is not.
5. Real-World Use Case: Validating User Input
In a real-world scenario, you might need to validate user input and throw IllegalArgumentException for invalid input.
Example: Validating User Input
fun registerUser(username: String?, age: Int) {
requireNotNull(username) { "Username cannot be null" }
require(username.length >= 3) { "Username must be at least 3 characters long" }
require(age >= 18) { "User must be at least 18 years old" }
println("User registered: $username, age $age")
}
fun main() {
try {
registerUser("John", 17)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
try {
registerUser(null, 20)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
try {
registerUser("Jo", 20)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
try {
registerUser("John", 20)
} catch (e: IllegalArgumentException) {
println("Caught an illegal argument exception: ${e.message}")
}
}
Output:
Caught an illegal argument exception: User must be at least 18 years old
Caught an illegal argument exception: Username cannot be null
Caught an illegal argument exception: Username must be at least 3 characters long
User registered: John, age 20
Explanation:
This example validates the username and age for a user registration and throws IllegalArgumentException for invalid input.
Conclusion
IllegalArgumentException in Kotlin is a standard exception that indicates an illegal or inappropriate argument passed to a method. By understanding how to handle IllegalArgumentException using try-catch blocks and validation functions like require and requireNotNull, you can write more robust and error-resistant code. Proper argument validation is crucial in real-world applications to ensure data integrity and prevent runtime exceptions.
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