Kotlin Exceptions
An exception signals that something went wrong at runtime: a file is missing, text isn't a number, an index is out of range. If nobody handles it, the program stops with an error message. Kotlin's exception handling looks like Java's, with two important differences: try is an expression, and there are no checked exceptions.
An unhandled exception
fun main() {
println("Start")
val n = "12a".toInt()
println("Never reached: $n")
}Start
Exception in thread "main" java.lang.NumberFormatException: For input string: "12a"
try / catch / finally
Code that might fail goes in try. A matching catch block handles the exception; finally always runs, whether an exception happened or not — good for cleanup.
fun main() {
val inputs = listOf("10", "zero", "5")
for (s in inputs) {
try {
val n = s.toInt()
println("100 / $n = ${100 / n}")
} catch (e: NumberFormatException) {
println("'$s' is not a number")
} finally {
println("-- checked '$s'")
}
}
}100 / 10 = 10
-- checked '10'
'zero' is not a number
-- checked 'zero'
100 / 5 = 20
-- checked '5'
You can have several catch blocks; the first matching one wins, so put specific types before general ones like Exception.
try is an expression
The value of try is the last expression of the try block, or of the catch block that ran:
fun parseAge(text: String): Int = try {
text.trim().toInt()
} catch (e: NumberFormatException) {
-1
}
fun main() {
println(parseAge(" 34 "))
println(parseAge("old"))
}34
-1
Throwing exceptions
Use throw with an exception object. require, check and error are concise built-ins for the most common cases:
| Function | Throws | Use for |
|---|---|---|
require(cond) { msg } |
IllegalArgumentException |
invalid arguments |
check(cond) { msg } |
IllegalStateException |
invalid state |
error(msg) |
IllegalStateException |
"should never get here" |
requireNotNull(x) { msg } |
IllegalArgumentException |
null arguments |
class Account(var balance: Int) {
var locked = false
fun withdraw(amount: Int) {
require(amount > 0) { "Amount must be positive, was $amount" }
check(!locked) { "Account is locked" }
if (amount > balance) throw IllegalArgumentException("Insufficient funds")
balance -= amount
}
}
fun main() {
val acc = Account(100)
val attempts = listOf(30, -5, 500)
for (a in attempts) {
try {
acc.withdraw(a)
println("Withdrew $a, balance ${acc.balance}")
} catch (e: IllegalArgumentException) {
println("Rejected: ${e.message}")
}
}
acc.locked = true
try {
acc.withdraw(10)
} catch (e: IllegalStateException) {
println("Error: ${e.message}")
}
}Withdrew 30, balance 70
Rejected: Amount must be positive, was -5
Rejected: Insufficient funds
Error: Account is locked
Custom exceptions
Create your own exception types by extending Exception (or a more specific class):
class OutOfStockException(val product: String) : Exception("$product is out of stock")
fun order(product: String, stock: Map<String, Int>) {
if ((stock[product] ?: 0) == 0) throw OutOfStockException(product)
println("Ordered $product")
}
fun main() {
val stock = mapOf("tea" to 3, "coffee" to 0)
for (p in listOf("tea", "coffee")) {
try {
order(p, stock)
} catch (e: OutOfStockException) {
println("Sorry: ${e.message}")
}
}
}Ordered tea
Sorry: coffee is out of stock
runCatching and Result
runCatching { … } wraps the outcome in a Result object instead of throwing — handy for functional-style code:
fun main() {
val ok = runCatching { "42".toInt() }
val bad = runCatching { "x".toInt() }
println(ok.getOrNull())
println(bad.getOrDefault(0))
println(bad.isFailure)
println(bad.exceptionOrNull()?.javaClass?.simpleName)
}42
0
true
NumberFormatException
Note: Kotlin has no checked exceptions: you never have to declare
throwsor catch an exception just to satisfy the compiler. Document important ones with the KDoc@throwstag, and use@Throwsif Java callers need to know.
Tip: Don't use exceptions for ordinary control flow. For expected "no result" cases, return
null(liketoIntOrNull()) or a sealed result type.
Test yourself
When does a finally block run?
- Only if an exception occurred
- Only if no exception occurred
- Always, after try/catch
- Never in Kotlin
Which exception does require(false) { "bad" } throw?
- IllegalStateException
- IllegalArgumentException
- RuntimeException
- AssertionError
Does Kotlin force you to catch or declare checked exceptions?
- Yes, like Java
- No, Kotlin has no checked exceptions
- Only for IOException
- Only in main