Intermediate 7 min readKotlin 2.0
Kotlin Exception Handling โ try, catch, finally
Exceptions handle unexpected errors at runtime. Kotlin uses try/catch/finally, and try can also be used as an expression.
What You Will Learn
- Basic try/catch/finally
- Catch specific exception types
- Use try as an expression
- Throw custom exceptions
- Kotlin vs Java checked exceptions
Basic try / catch / finally
Wrap risky code in try. Handle errors in catch. finally always runs.
try/catch/finally
kotlin
fun main() {
try {
val result = 10 / 0
println(result)
} catch (e: ArithmeticException) {
println("Cannot divide by zero: ${e.message}")
} finally {
println("This always runs")
}
}Output
Cannot divide by zero: / by zero
This always runs
Division by zero throws ArithmeticException. catch catches it and prints the message. finally runs whether or not an exception occurred.
Beginner Tip: finally is used to release resources โ close files, database connections, network sockets โ regardless of success or failure.
Multiple catch Blocks
Catch different exceptions in separate blocks.
Multiple catch
kotlin
fun parseAndDouble(input: String): Int {
return try {
input.toInt() * 2
} catch (e: NumberFormatException) {
println("Not a number: $input")
0
} catch (e: Exception) {
println("Unexpected error: ${e.message}")
-1
}
}
fun main() {
println(parseAndDouble("5"))
println(parseAndDouble("abc"))
}Output
10
Not a number: abc
0
Specific exceptions are caught first. The general Exception catch is a fallback. try returns a value โ the last expression in each branch.
Custom Exceptions
Create custom exception classes by extending Exception.
Custom Exception
kotlin
class InsufficientFundsException(amount: Double) :
Exception("Insufficient funds: need $${"%.2f".format(amount)}")
fun withdraw(balance: Double, amount: Double): Double {
if (amount > balance) throw InsufficientFundsException(amount - balance)
return balance - amount
}
fun main() {
try {
val bal = withdraw(100.0, 150.0)
println("Balance: $bal")
} catch (e: InsufficientFundsException) {
println(e.message)
}
}Output
Insufficient funds: need $50.00
Custom exceptions extend Exception. throw creates and throws the exception. The message is available via e.message.
Best Practice: Create specific exception types for domain errors. They make catch blocks explicit and improve error messages.
Practice Exercise
Exercisepredict output
What prints? val result = try { "42".toInt() } catch (e: NumberFormatException) { 0 } println(result)
Quick Quiz
Quick Quiz
Does Kotlin have checked exceptions like Java?
Frequently Asked Questions
Related Tutorials
Last updated: 2026-05-01Kotlin 2.0
Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review