Kotlin ArithmeticException
On the JVM, division of an Int by a zero denominator throws ArithmeticException.
A simple example
ArithmeticException
- Start with 4 divided into zero groups
- Do this Attempt integer division or check the divisor
- Result Division cannot proceed
Syntax
fee / students
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarSplit an equipment fee across a class
A training center shares a fixed equipment fee among the students registered for a workshop. When the last student cancels, the fee calculator should show a message before it divides by the headcount.
fun main() {
val registrations = emptyList<String>()
try {
println(120 / registrations.size)
} catch (emptyClass: ArithmeticException) {
println("No students registered")
}
}
No students registered
The workshop has zero students, so the calculator cannot assign anyone a share of the fee.
Split a studio hire fee
Two groups register for a 24-credit rehearsal. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.
Hold an empty field-trip batch
A trip has a 30-credit fixed fee and no groups registered yet. Divide the total among the registered groups using whole-number division. The desk puts the batch on hold if the divisor is zero.
What to watch for
A Double denominator follows floating-point rules. Check the headcount before calculating an average.