0
0
Kotlinprogramming~20 mins

RunCatching for safe execution in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
RunCatching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this RunCatching example?
Consider this Kotlin code using runCatching. What will it print?
Kotlin
val result = runCatching {
    val number = "123a".toInt()
    number * 2
}.getOrElse {
    -1
}
println(result)
AException in thread "main" java.lang.NumberFormatException
B0
C-1
D246
Attempts:
2 left
💡 Hint
Think about what happens when toInt() fails inside runCatching.
Predict Output
intermediate
2:00remaining
What does this runCatching block return?
Analyze this Kotlin snippet using runCatching. What is the value of output?
Kotlin
val output = runCatching {
    val list = listOf(1, 2, 3)
    list[5]
}.getOrNull()
println(output)
AIndexOutOfBoundsException
Bnull
C3
D5
Attempts:
2 left
💡 Hint
What happens when you access an invalid index inside runCatching?
🔧 Debug
advanced
2:00remaining
Why does this runCatching block not catch the exception?
Look at this Kotlin code. Why does the exception still crash the program?
Kotlin
val result = runCatching {
    throw IllegalStateException("Error happened")
}.getOrElse {
    throw it
}
println("Done")
ABecause getOrElse rethrows the exception, so it is not handled.
BBecause println("Done") is unreachable and causes a compile error.
CBecause the exception is thrown outside runCatching block.
DBecause runCatching only catches IOException, not IllegalStateException.
Attempts:
2 left
💡 Hint
Check what getOrElse does with the caught exception.
📝 Syntax
advanced
2:00remaining
Which option correctly uses runCatching to safely parse an integer?
Choose the Kotlin code snippet that safely parses a string to an integer using runCatching and returns 0 if parsing fails.
Aval number = runCatching { "42".toInt() }.getOrElse { 0 }
Bval number = runCatching { "42".toInt() } ?: 0
Cval number = runCatching { "42".toInt() }.getOrDefault(0)
Dval number = runCatching { "42".toInt() }.getOrNull() ?: 0
Attempts:
2 left
💡 Hint
Remember how getOrElse works compared to getOrDefault and getOrNull.
🚀 Application
expert
3:00remaining
How many items are in the list after this runCatching chain?
Given this Kotlin code, how many items does results contain after execution?
Kotlin
val inputs = listOf("10", "abc", "20", "-5")
val results = inputs.mapNotNull { input ->
    runCatching { input.toInt() }
        .getOrNull()
}.filter { it > 0 }
A3
B1
C4
D2
Attempts:
2 left
💡 Hint
Count how many strings convert to positive integers successfully.