KtKotlin
IntermediateLesson 12 of 16

Error Handling & Files – Kotlin

try as an expression, require/check, runCatching, and file access.

Kotlin has no checked exceptions: you do not have to declare or catch errors. try is an expression and returns a value. You inherit your own errors from Exception.

val zahl = try {
    "abc".toInt()
} catch (e: NumberFormatException) {
    -1
}
println(zahl)                                        // -1

class KontoFehler(message: String) : Exception(message)

fun abheben(saldo: Int, betrag: Int): Int {
    if (betrag > saldo) throw KontoFehler("Only $saldo available")
    return saldo - betrag
}

try {
    abheben(50, 100)
} catch (e: KontoFehler) {
    println("Error: ${e.message}")                    // Error: Only 50 available
} finally {
    println("done")
}

To check preconditions there are require (wrong arguments → IllegalArgumentException), check (wrong state → IllegalStateException), and error(...). With runCatching you wrap a result in a Result:

fun setzeAlter(alter: Int) {
    require(alter in 0..150) { "Invalid age: $alter" }
}

val r = runCatching { setzeAlter(-5) }
println(r.isFailure)                        // true
println(r.exceptionOrNull()?.message)       // Invalid age: -5
println(runCatching { "42".toInt() }.getOrDefault(-1))   // 42

You read and write files with java.io.File and the Kotlin extensions. use and useLines close resources automatically (like try-with-resources).

import java.io.File

val datei = File("notizen.txt")
datei.writeText("Line 1\nLine 2\n")
println(datei.readText().length)             // 14
println(datei.readLines())                   // [Line 1, Line 2]
datei.appendText("Line 3\n")
datei.useLines { zeilen -> println(zeilen.count()) }   // 3
datei.bufferedReader().use { println(it.readLine()) }  // Line 1
WarningreadText() and readLines() load the entire file into memory. For large files, use useLines or forEachLine, which work line by line.