Kotlin error()

Kotlin error()

The error() function in Kotlin is used to throw an IllegalStateException with the specified error message.

error() function is often used for situations where the program encounters a state that should not be possible.

In this tutorial, we shall go through syntax and examples for Kotlin error() function.

Syntax

The syntax of the error() function is:

fun error(message: Any): Nothing

where

ParameterDescription
messageThe error message to be included in the thrown exception.
Parameter of error() function

The function returns Nothing, indicating that it does not return a value as it always throws an exception.

Examples

1. Using error() for Custom Error Handling

In this example, we’ll use error() to throw a custom exception when a specific condition is not met.

Kotlin Program

fun processInput(input: String) {
    if (input.isEmpty()) {
        error("Input should not be empty")
    }

    // Process the input if the condition is met
    println("Processing input: $input")
}

fun main() {
    processInput("Hello, Kotlin!")
    processInput("") // This will throw an IllegalStateException
}

Output

Processing input: Hello, Kotlin!
Exception in thread "main" java.lang.IllegalStateException: Input should not be empty
	at MainKt.processInput(Main.kt:3)
	at MainKt.main(Main.kt:12)
	at MainKt.main(Main.kt)

In this example, the error() function is used to throw an exception with a custom error message when the condition is not met.

Summary

The error() function in Kotlin is a concise way to throw an IllegalStateException with a custom error message. It is useful for handling unexpected or invalid states in the program.