Error handling
- Kotlin course
- Beginner
- Lesson 22/116
- 6 min
Safely catch invalid inputs with try/catch.
What is try/catch?
Sometimes an operation throws an exception; for example, division by zero, a missing file, or a number conversion error. With try/catch you can catch these exceptions and prevent the program from crashing.
try {
println(divide(10, 2))
} catch (e: ArithmeticException) {
println("Division by zero")
}The try block runs the risky operation; if an exception is thrown, the catch block runs.
What is finally?
The finally block runs after try/catch in every case; whether an exception is thrown or not. It is usually used to close files or release resources.
Although Kotlin's use function does this automatically, finally is still a tool worth knowing. We won't use it directly in the calculator but knowing the basics matters.
Practice Wrap divide in try/catch
Inside the existing main, wrap the println(divide(10, 2)) call in try { ... } catch (e: ArithmeticException) { println("Division by zero") }. Keep all other calls.
Starter code
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a - b
}
fun multiply(a: Int, b: Int): Int {
return a * b
}
fun divide(a: Int, b: Int): Int {
if (b == 0) {
return 0
}
return a / b
}
fun main() {
println("Calculator")
println(add(5, 3))
println(subtract(5, 3))
println(multiply(5, 3))
println(divide(10, 2))
}Sample solution
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a - b
}
fun multiply(a: Int, b: Int): Int {
return a * b
}
fun divide(a: Int, b: Int): Int {
if (b == 0) {
return 0
}
return a / b
}
fun main() {
println("Calculator")
println(add(5, 3))
println(subtract(5, 3))
println(multiply(5, 3))
try {
println(divide(10, 2))
} catch (e: ArithmeticException) {
println("Division by zero")
}
}Expected output
Calculator 8 2 15 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does try/catch do?
- Sends code to the compiler
- Catches errors and prevents crash Correct answer
- Starts a loop
- Declares a variable
Explanation: try/catch catches exceptions and prevents crashes.
2 Complete the catch block
try { println(divide(10, 0)) } ____ (e: ArithmeticException) { println("Division by zero") }
try { println(divide(10, 0)) } catch (e: ArithmeticException) { println("Division by zero") }
Explanation: catch catches the exception.
3 Match the exception concepts
| Term | Meaning |
|---|---|
try |
Try |
catch |
Catch |
finally |
Cleanup |
throw |
Throw |