BeginnerExceptions
try catch finally
Handle runtime errors gracefully.
kotlin
fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Cannot divide by zero")
} finally {
println("Program completed")
}
}Output
Cannot divide by zero
Program completed
Explanation
try runs the risky code. catch handles the specific exception. finally always runs regardless of success or failure.