throw
- Kotlin course
- Beginner
- Lesson 101/116
- 4 min
Learn to throw exceptions with throw.
throw: raise your own error
When a condition is met, you can raise an error with throw. This is the basic way to catch invalid input early.
fun checkAge(age: Int) {
if (age < 0)
throw IllegalArgumentException("Age cannot be negative")
}throw raises an object; it is an instance of an exception class. When raised, the rest of the function does not run. The caller catches it with try/catch.
Common exception types
Kotlin provides ready exception classes for common cases. Their names explain the situation; picking the right type matters.
throw IllegalArgumentException("Bad input")
throw IllegalStateException("Wrong state")
throw NullPointerException("Null access")IllegalArgumentException is for bad input, IllegalStateException for wrong time or state, NullPointerException for accessing a null object. The right type shows the cause clearly.
Practice Throw on a negative age
Write fun checkAge(age: Int); if age is below 0, throw IllegalArgumentException("Age cannot be negative"). In main call checkAge(-1); catch it with try/catch and print the message.
Starter code
fun main() {
// Write an age check; throw on negative and catch in main
}Sample solution
fun checkAge(age: Int) {
if (age < 0) throw IllegalArgumentException("Age cannot be negative")
}
fun main() {
try {
checkAge(-1)
} catch (e: IllegalArgumentException) {
println(e.message)
}
}Expected output
Yaş negatif olamaz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: raise the error
if (age < 0) ____ IllegalArgumentException("Age cannot be negative")
if (age < 0) throw IllegalArgumentException("Age cannot be negative")
Explanation: throw IllegalArgumentException raises the error.
2 When does throw run?
- When the condition is met Correct answer
- Always
- Never
- Only when no error
Explanation: throw runs only when its line is reached.
3 Match exception to scenario
| Term | Meaning |
|---|---|
IllegalArgumentException |
Bad input |
IllegalStateException |
Wrong state |
NullPointerException |
Null object |
ArithmeticException |
Math error |