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.
Comments
Post a Comment
Leave Comment