Kotlin Exceptions
An exception is a problem report a program creates when it cannot finish a job. Throwing an exception hands the problem to code that can handle it.
Throwing and catching in main
The throw creates an IllegalArgumentException with a message. The catch prints that message.
fun main() {
try {
throw IllegalArgumentException("Name is empty")
} catch (e: IllegalArgumentException) {
println(e.message)
}
}A check that throws
checkAge throws when the age is negative. The catch in main prints the message.
fun checkAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
println("Age is $age")
}
fun main() {
try {
checkAge(-1)
} catch (e: IllegalArgumentException) {
println(e.message)
}
}A call that passes the check
The age 25 passes the check inside checkAge. The normal print runs and the catch stays unused.
fun checkAge(age: Int) {
if (age < 0) {
throw IllegalArgumentException("Age cannot be negative")
}
println("Age is $age")
}
fun main() {
try {
checkAge(25)
} catch (e: IllegalArgumentException) {
println(e.message)
}
println("Program continues")
}Example
fun checkScore(score: Int) {
if (score < 0 || score > 100) {
throw IllegalArgumentException("Score must be from 0 to 100")
}
println("Score $score is valid")
}
fun main() {
try {
checkScore(150)
} catch (e: IllegalArgumentException) {
println(e.message)
}
checkScore(80)
}Key points
- Exception: a problem report created when a program cannot finish a job
- Use throw to create an exception at a problem point
- IllegalArgumentException reports a bad argument value
- A try block holds code that may throw an exception
- A catch block handles an exception from the try block
- Use e.message to read the text stored in an exception
In this example, checkScore throws for the score 150 because the score is above 100. The catch prints the message from the exception. The second call with 80 passes the check and prints its valid line.
Note
An exception that no code catches stops the program.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does throw do?