0
0
Kotlinprogramming~20 mins

Try-catch as an expression in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Try-Catch Expression Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try-catch expression with successful try block
What is the output of this Kotlin code snippet?
Kotlin
val result = try {
    val x = 10 / 2
    "Success: $x"
} catch (e: ArithmeticException) {
    "Error"
}
println(result)
ASuccess: 5
BError
C10
DCompilation error
Attempts:
2 left
💡 Hint
Remember that try-catch in Kotlin can return a value from the try block if no exception occurs.
Predict Output
intermediate
2:00remaining
Output when exception is thrown in try block
What will be printed by this Kotlin code?
Kotlin
val result = try {
    val x = 10 / 0
    "Success: $x"
} catch (e: ArithmeticException) {
    "Error caught"
}
println(result)
ASuccess: 0
BError caught
CArithmeticException thrown
DCompilation error
Attempts:
2 left
💡 Hint
Division by zero throws an exception, so the catch block runs.
Predict Output
advanced
2:00remaining
Value of variable after try-catch expression with finally
What is the value of variable 'result' after running this Kotlin code?
Kotlin
val result = try {
    "Try block"
} catch (e: Exception) {
    "Catch block"
} finally {
    println("Finally block executed")
}
println(result)
ACompilation error
BCatch block
Cnull
DTry block
Attempts:
2 left
💡 Hint
Finally block runs but does not affect the returned value.
Predict Output
advanced
2:00remaining
Output when catch block throws exception in try-catch expression
What happens when this Kotlin code runs?
Kotlin
val result = try {
    val x = 10 / 0
    "Success"
} catch (e: ArithmeticException) {
    throw IllegalStateException("New exception")
}
println(result)
AIllegalStateException is thrown
BSuccess
CCompilation error
DArithmeticException is caught and printed
Attempts:
2 left
💡 Hint
The catch block throws a new exception instead of returning a value.
🧠 Conceptual
expert
2:00remaining
Why is try-catch an expression in Kotlin?
Which statement best explains why try-catch is an expression in Kotlin?
ABecause it can only be used inside functions that return Unit.
BBecause it only handles exceptions without returning any value.
CBecause it can return a value from either the try or catch block, allowing assignment to variables.
DBecause it requires a finally block to compile successfully.
Attempts:
2 left
💡 Hint
Think about how try-catch can be used in assignments.