0
0
Kotlinprogramming~20 mins

Throw as an expression in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Throw Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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))
}
A5
BIllegalArgumentException thrown
C0
DCompilation error
Attempts:
2 left
💡 Hint
Remember that throw can be used as an expression in Kotlin.
Predict Output
intermediate
2: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))
}
APrints -1
BPrints 0
CThrows IllegalArgumentException with message "Negative value"
DCompilation error
Attempts:
2 left
💡 Hint
Check what happens when value is not greater than 0.
🔧 Debug
advanced
2: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
}
Aif expression must have else branch returning Int
BVariable result is not initialized
CMissing return statement
Dthrow must throw a Throwable, not a String
Attempts:
2 left
💡 Hint
Check the type of the expression after throw.
🧠 Conceptual
advanced
2: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))
}
AThrows IllegalArgumentException with message "Value required"
BPrints null
CPrints empty string
DCompilation error
Attempts:
2 left
💡 Hint
Consider what the Elvis operator does when the left side is null.
Predict Output
expert
3: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)
    }
}
A123\nException in thread "main" java.lang.NumberFormatException
B123\nInvalid number
CInvalid number\n123
DCompilation error
Attempts:
2 left
💡 Hint
Check how the exception is caught and handled in main.