Throwing an error can be used as a value in Kotlin. This helps write shorter and clearer code by combining error handling with expressions.
Throw as an expression in 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.
name is null, the program throws an error instead of assigning a value.val name: String? = null val safeName = name ?: throw IllegalArgumentException("Name required")
num if not null, otherwise throws an error.fun getNumber(num: Int?): Int = num ?: throw NullPointerException("Number missing")
val age = 20 val category = if (age >= 18) "Adult" else throw Exception("Too young")
This program tries to assign input to result. Since input is null, it throws an error instead of printing.
fun main() { val input: String? = null val result = input ?: throw IllegalStateException("Input cannot be null") println("Result: $result") }
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.
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.
Practice
What does the throw keyword do when used as an expression in Kotlin?
Solution
Step 1: Understand the role of
Thethrowthrowkeyword is used to signal an error by throwing an exception.Step 2: Recognize its effect in expressions
When used as an expression,throwstops the current execution and throws the specified exception immediately.Final Answer:
It immediately stops execution and throws an exception. -> Option CQuick Check:
throw= stops and throws error [OK]
- Thinking throw returns a normal value
- Confusing throw with return
- Assuming throw creates variables
Which of the following is the correct way to use throw as an expression in Kotlin?
val number = if (input > 0) input else ???
Solution
Step 1: Check Kotlin syntax for throw expression
In Kotlin,throwis used withoutnewkeyword and can be used as an expression.Step 2: Match the correct usage in the if-else expression
The correct syntax isthrow IllegalArgumentException("message")withoutnewand it fits as an expression in else branch.Final Answer:
throw IllegalArgumentException("Input must be positive") -> Option AQuick Check:
Throw expression syntax = throw IllegalArgumentException("Input must be positive") [OK]
- Using 'new' keyword with throw
- Using return instead of throw
- Trying to print error instead of throwing
What will be the output of this Kotlin code?
fun getName(name: String?): String {
return name ?: throw IllegalArgumentException("Name required")
}
fun main() {
println(getName(null))
}Solution
Step 1: Analyze the Elvis operator with throw
The expressionname ?: throw IllegalArgumentException("Name required")returnsnameif not null, else throws the exception.Step 2: Check the input and output
SincegetName(null)is called,nameis null, so the exception is thrown and program crashes with that message.Final Answer:
Exception in thread "main" java.lang.IllegalArgumentException: Name required -> Option DQuick Check:
Throw in Elvis operator throws exception [OK]
- Expecting null to print
- Thinking exception message prints normally
- Assuming code compiles but returns empty string
Identify the error in this Kotlin code snippet:
val age = 20 val validAge = if (age >= 18) age else throw "Age must be 18 or older"
Solution
Step 1: Check the throw expression type
In Kotlin,throwmust throw an object of typeThrowable, not a plain String.Step 2: Identify the error in else branch
The code tries to throw a String literal, which is invalid and causes a compilation error.Final Answer:
Cannot throw a String, must throw an Exception object. -> Option AQuick Check:
Throw must be Exception, not String [OK]
- Throwing plain strings instead of exceptions
- Missing braces but code compiles anyway
- Confusing throw with return
Given this Kotlin function:
fun parseNumber(input: String?): Int {
val number = input?.toIntOrNull() ?: throw NumberFormatException("Invalid number")
return number
}What will parseNumber(null) do, and why is throw used as an expression here?
Solution
Step 1: Understand the Elvis operator with throw
The expressioninput?.toIntOrNull() ?: throw NumberFormatException("Invalid number")tries to convert input to Int or throws if null or invalid.Step 2: Analyze behavior when input is null
Since input is null,toIntOrNull()returns null, so the throw expression executes, throwing the exception immediately.Step 3: Reason why throw is used as expression
Using throw as expression allows combining error handling with assignment in one line, making code concise and readable.Final Answer:
Throws NumberFormatException because input is null; throw used to combine error and assignment. -> Option BQuick Check:
Throw expression combines error and value assignment [OK]
- Thinking null converts to zero
- Confusing throw as statement only
- Ignoring exception thrown on null input
Ready to prove it?
Pass the test and this pattern moves unknown
