Complete the code to catch exceptions inside a coroutine.
launch {
try {
// Some suspending function
fetchData()
} catch ([1]: Exception) {
println("Error caught")
}
}The variable e is commonly used to catch exceptions in Kotlin. It holds the caught exception object.
Complete the code to handle exceptions globally in a CoroutineScope.
val handler = CoroutineExceptionHandler { _, [1] ->
println("Caught $[1]")
}
CoroutineScope(Dispatchers.Default + handler).launch {
throw RuntimeException("Fail")
}The CoroutineExceptionHandler receives a Throwable as the second parameter, commonly named throwable.
Fix the error in the coroutine exception handling code.
val handler = CoroutineExceptionHandler { _, throwable ->
println("Caught: $[1]")
}
GlobalScope.launch(handler) {
throw Exception("Oops")
}The variable throwable is the correct name used in the lambda parameter and must be referenced inside the lambda.
Fill both blanks to create a map of word lengths filtering words longer than 3 characters.
val words = listOf("cat", "house", "dog", "elephant") val lengths = words.associateWith { it.[1] } .filter { it.value [2] 3 }
count without parentheses which is a function.length gets the length of the string, and > filters words longer than 3 characters.
Fill all three blanks to create a map of uppercase keys and values filtered by positive values.
val data = mapOf("a" to 1, "b" to -2, "c" to 3) val result = data.mapKeys { it.key.[1]() } .filter { it.value [2] 0 } .mapValues { it.[3] }
toLowerCase() instead of uppercase.key instead of value in mapValues.toUpperCase() converts keys to uppercase, > filters positive values, and value returns the map's value.