Challenge - 5 Problems
Throw Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of throw as an expression in Kotlin
What is the output of this Kotlin code snippet?
Kotlin
fun test(value: Int): Int { val result = if (value > 0) value else throw IllegalArgumentException("Negative value") return result } fun main() { println(test(5)) }
Attempts:
2 left
💡 Hint
Remember that throw can be used as an expression in Kotlin.
✗ Incorrect
Since the value is 5 which is greater than 0, the if expression returns 5 and no exception is thrown.
❓ Predict Output
intermediate2:00remaining
Exception thrown with throw as expression
What happens when this Kotlin code runs?
Kotlin
fun test(value: Int): Int { val result = if (value > 0) value else throw IllegalArgumentException("Negative value") return result } fun main() { println(test(-1)) }
Attempts:
2 left
💡 Hint
Check what happens when value is not greater than 0.
✗ Incorrect
Since value is -1, the else branch throws an IllegalArgumentException with the given message.
🔧 Debug
advanced2:00remaining
Identify the error with throw as expression
Why does this Kotlin code cause a compilation error?
Kotlin
fun test(value: Int): Int { val result = if (value > 0) value else throw "Error" return result }
Attempts:
2 left
💡 Hint
Check the type of the expression after throw.
✗ Incorrect
In Kotlin, throw must throw an object of type Throwable or its subclass, not a String.
🧠 Conceptual
advanced2:00remaining
Using throw as an expression in Elvis operator
What is the output of this Kotlin code?
Kotlin
fun test(value: String?): String { return value ?: throw IllegalArgumentException("Value required") } fun main() { println(test(null)) }
Attempts:
2 left
💡 Hint
Consider what the Elvis operator does when the left side is null.
✗ Incorrect
The Elvis operator returns the left side if not null; otherwise, it evaluates the right side which throws an exception.
❓ Predict Output
expert3:00remaining
Throw as expression in complex return statement
What is the output of this Kotlin program?
Kotlin
fun parseIntOrThrow(input: String): Int { return input.toIntOrNull() ?: throw NumberFormatException("Invalid number") } fun main() { try { println(parseIntOrThrow("123")) println(parseIntOrThrow("abc")) } catch (e: NumberFormatException) { println(e.message) } }
Attempts:
2 left
💡 Hint
Check how the exception is caught and handled in main.
✗ Incorrect
The first call prints 123. The second call throws NumberFormatException caught by catch block, printing the message.