bhylu.com

Advertisements

Kotlin Exceptions

Use a specific failure contract and catch only the failure you can handle.

How it works

require checks a caller precondition and throws IllegalArgumentException. check expresses an internal state assertion and throws IllegalStateException. try can be an expression. Catch specific expected failures at an appropriate boundary rather than swallowing every exception.

Run this Kotlin example

These are local Kotlin/JVM programs. Install a JDK and the compiler using the official Kotlin compiler guide, or use an IDE with Kotlin support. Check java -version and kotlinc -version in a new terminal. The reviewed compiler is Kotlin 2.4.21 with a JVM 21 target, executed on Temurin JDK 25.0.5. Use JDK 21 or newer for this target. Android, Kotlin/JS and Kotlin/Native require separate platform projects and are not the tested environment here.

Save the complete source as exceptions.kt in its own learning folder. The package line gives this example a namespace, not a network address. Bhylu has no Kotlin browser runner; do not use the JavaScript or Python editor. Apache, PHP and MySQL are not required.

Compile with kotlinc exceptions.kt -jvm-target 21 -include-runtime -d lesson.jar, then run java -jar lesson.jar. Use a learning folder you own and keep generated JARs outside the website. These sources require no third-party application libraries.

Download the complete exceptions.kt · Download all source files with hash checks

For the optional collection, save download-examples.mjs in a new learning folder and run node download-examples.mjs. A local preview uses node download-examples.mjs http://127.0.0.1:8000/examples/kotlin/. It refuses an existing bhylu-kotlin-examples folder and installs or executes no Kotlin code. Compile one ordinary lesson at a time by filename.

Example

exceptions.kt

package bhylu.lessons.k_exceptions

fun parseMinutes(raw: String): Int {
    val minutes = raw.toIntOrNull() ?: throw IllegalArgumentException("Need whole minutes")
    require(minutes in 1..240) { "Minutes must be 1..240" }
    return minutes
}

fun main() {
    for (text in listOf("30", "-1", "bad")) {
        val notice = try {
            "Minutes: " + parseMinutes(text)
        } catch (error: IllegalArgumentException) {
            "Invalid duration"
        }
        println(notice)
    }
}

Expected result

Minutes: 30
Invalid duration
Invalid duration

The parser first checks integer syntax, then the accepted range. Its caller turns that specific contract failure into a notice. In an ordinary UI, a typed result may be more convenient for routine rejected input.

For exact language and library contracts, consult the official Kotlin documentation. These fictional fixtures are learning programs, not a deployed hire service.

Advertisements