Skip to main content
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.

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:
Within a when Expression:

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.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More