Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

In Kotlin, throw is an expression rather than a statement. It is used to explicitly raise an exception at runtime, terminating the normal execution of the current scope. Because it evaluates as an expression, it possesses a distinct type in the Kotlin type system, allowing it to be composed directly within other expressions.

Syntax

The throw keyword must be followed by an expression that evaluates to an instance of a Throwable class. This can be a direct instantiation, a variable reference, or a function call that returns a Throwable.
// Direct instantiation
throw IllegalArgumentException("Invalid argument")

// Variable reference
val exception = IllegalStateException("Invalid state")
throw exception

The Nothing Type

The evaluation type of a throw expression is Nothing. In Kotlin’s type hierarchy, Nothing is a bottom type, meaning it is a subtype of every other type. Because a throw expression never successfully evaluates to a value (it unconditionally transfers control flow to the nearest exception handler), the compiler allows it to be used in any context where a specific data type is expected.

Expression Composition

The Nothing return type allows throw to be seamlessly integrated into expressions that require a unified return type, such as the Elvis operator (?:) or when expressions. With the Elvis Operator:
val text: String? = null

// The compiler expects an Int on the right side of ?: because text?.length evaluates to Int?.
// 'throw' evaluates to Nothing, which acts as a valid subtype of Int in this context.
val length: Int = text?.length ?: throw IllegalArgumentException("Text cannot be null")
Within a when Expression:
val status: String = "UNKNOWN"

// The 'when' expression must evaluate to an Int.
// The 'else' branch evaluates to Nothing, satisfying the type checker.
val code: Int = when (status) {
    "SUCCESS" -> 200
    "ERROR" -> 500
    else -> throw IllegalStateException("Unrecognized status")
}

Control Flow and Smart Casting

The Kotlin compiler performs control flow analysis around throw expressions.
  1. Unreachable Code: Any code sequentially following a throw expression within the same block is marked as unreachable by the compiler.
  2. Smart Casting: If a throw expression is used to guard against a specific state (such as nullability or type checking), the compiler applies smart casting to the checked variable for all subsequent execution paths within that scope.
fun process(data: Any?) {
    // Guard condition using throw
    if (data !is String) throw TypeCastException("Data must be a String")
    
    // Control flow analysis guarantees 'data' is smart cast to a non-nullable String here
    println(data.uppercase())
}
Master Kotlin with Deep Grasping Methodology!Learn More