0
0
Kotlinprogramming~10 mins

RunCatching for safe execution in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to safely execute the block using RunCatching.

Kotlin
val result = runCatching([1] {
    val number = "123".toInt()
    number * 2
})
Drag options to blanks, or click blank then click option'
A{}
B()
C() ->
D() -> Unit
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect lambda syntax like () -> Unit or {} which are not valid here.
2fill in blank
medium

Complete the code to get the result value or null if an exception occurs.

Kotlin
val result = runCatching {
    "abc".toInt()
}.[1]()
Drag options to blanks, or click blank then click option'
AgetOrNull
BgetOrThrow
CgetOrDefault
DgetOrElse
Attempts:
3 left
💡 Hint
Common Mistakes
Using getOrThrow() which throws the exception instead of returning null.
3fill in blank
hard

Fix the error in the code to handle failure with onFailure.

Kotlin
runCatching {
    val x = 10 / 0
}.[1] {
    println("Error: ${it.message}")
}
Drag options to blanks, or click blank then click option'
AonSuccess
BonFailure
CgetOrNull
DgetOrElse
Attempts:
3 left
💡 Hint
Common Mistakes
Using onSuccess which runs only if no exception occurred.
4fill in blank
hard

Fill both blanks to create a map of word lengths only for words longer than 3 characters.

Kotlin
val words = listOf("cat", "house", "dog", "elephant")
val lengths = words.associateWith { [1] }
    .filter { it.value [2] 3 }
Drag options to blanks, or click blank then click option'
Ait.length
B>
C<
Dit.size
Attempts:
3 left
💡 Hint
Common Mistakes
Using it.size which is invalid for String.
Using < instead of > in filter condition.
5fill in blank
hard

Fill all three blanks to safely get uppercase words longer than 4 characters.

Kotlin
val words = listOf("apple", "bat", "carrot", "dog")
val safeWords = runCatching {
    words.map { it.[1]() }
}.getOrElse { emptyList() }
.filter { it.length [2] 4 }
.associateWith { it.length [3] 0 }
Drag options to blanks, or click blank then click option'
Auppercase
B>
C*
Duppercase()
Attempts:
3 left
💡 Hint
Common Mistakes
Using uppercase without parentheses which is not a function call.
Using < instead of > in filter.
Using + or - instead of * in multiplication.