Panic in Kotlin

In Kotlin, the concept of panic is not directly present. Instead, we use exceptions for unexpected errors. Here’s how we can implement similar behavior:

import java.io.File

fun main() {
    // We'll use exceptions throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to throw an exception.
    throw RuntimeException("a problem")

    // A common use of exceptions is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // throwing an exception if we get an unexpected error when creating a new file.
    try {
        File("/tmp/file").createNewFile()
    } catch (e: Exception) {
        throw RuntimeException(e)
    }
}

Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.

When the first exception in main is thrown, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first exception.

$ kotlin panic.kt
Exception in thread "main" java.lang.RuntimeException: a problem
	at MainKt.main(panic.kt:7)

Note that unlike some languages which use exceptions for handling of many errors, in Kotlin it is idiomatic to use nullable types and the Result type for error handling where possible. However, for truly unexpected errors, exceptions are still used.