0
0
Kotlinprogramming~5 mins

Throw as an expression in Kotlin

Choose your learning style9 modes available
Introduction

Throwing an error can be used as a value in Kotlin. This helps write shorter and clearer code by combining error handling with expressions.

When you want to stop a function and show an error if a condition is not met.
When you want to assign a value but throw an error if the value is missing or invalid.
When you want to use a throw inside a simple expression like an if or Elvis operator.
When you want to avoid writing extra lines for error checks and keep code clean.
Syntax
Kotlin
val result = someValue ?: throw Exception("Error message")

The throw keyword can be used wherever an expression is expected.

This means you can use it with operators like ?: (Elvis) or in assignments.

Examples
If name is null, the program throws an error instead of assigning a value.
Kotlin
val name: String? = null
val safeName = name ?: throw IllegalArgumentException("Name required")
This function returns num if not null, otherwise throws an error.
Kotlin
fun getNumber(num: Int?): Int = num ?: throw NullPointerException("Number missing")
Throw is used inside an if expression to handle the else case.
Kotlin
val age = 20
val category = if (age >= 18) "Adult" else throw Exception("Too young")
Sample Program

This program tries to assign input to result. Since input is null, it throws an error instead of printing.

Kotlin
fun main() {
    val input: String? = null
    val result = input ?: throw IllegalStateException("Input cannot be null")
    println("Result: $result")
}
OutputSuccess
Important Notes

Using throw as an expression helps reduce extra if-checks and makes code concise.

Remember that throwing stops the current function unless caught by a try-catch.

Summary

Throw as an expression lets you throw errors inside expressions like assignments or operators.

This makes your code shorter and easier to read by combining error handling with value assignment.