← All languages
Kotlin function of the day
Random

error

Throw an IllegalStateException with a message.

Description

The error function throws an IllegalStateException with the given message. It is a concise alternative to writing throw IllegalStateException(message).

This function has a return type of Nothing, which means it can be used in expressions and the compiler knows that code after it is unreachable. It is commonly used in when expressions to handle unexpected branches.

error is useful for signaling programming errors and impossible states.

Arguments

NameDescriptionOptional
message The error message for the exception. No

Example

fun getColor(name: String): Int = when (name) {
    "red" -> 0xFF0000
    "green" -> 0x00FF00
    "blue" -> 0x0000FF
    else -> error("Unknown color: $name")
}

Reference