Complete the code to catch exceptions inside a coroutine using try-catch.
launch {
try {
// some suspend function call
} catch (e: [1]) {
println("Error caught")
}
}In Kotlin coroutines, Exception is commonly caught to handle errors.
Complete the code to handle exceptions globally in a CoroutineScope using a handler.
val handler = CoroutineExceptionHandler { _, [1] ->
println("Caught: $[1]")
}
CoroutineScope(Dispatchers.Main + handler).launch {
// coroutine code
}The CoroutineExceptionHandler lambda receives the CoroutineContext and the exception object.
Fix the error in the code to properly handle cancellation exceptions separately.
try { withContext(Dispatchers.IO) { // some suspend call } } catch (e: [1]) { println("Cancelled") } catch (e: Exception) { println("Other error") }
CancellationException must be caught separately to handle coroutine cancellations properly.
Fill both blanks to create a supervisor scope that handles child coroutine failures independently.
supervisorScope {
val job = launch [1] {
throw RuntimeException("Fail")
}
job [2] {
println("Child failed")
}
}Using SupervisorJob() allows child coroutines to fail independently. invokeOnCompletion registers a callback on job completion.
Fill all three blanks to create a coroutine with a handler that logs exceptions and rethrows cancellation.
val handler = CoroutineExceptionHandler { _, e ->
if (e is [1]) throw e
else println("Error: $e")
}
CoroutineScope(Dispatchers.Default + handler).launch {
try {
// some suspend call
} catch (e: [2]) {
println("Caught: $e")
}
}
fun main() {
val job = CoroutineScope(Dispatchers.Default + handler).launch {
throw [3]("Oops")
}
}CancellationException is rethrown to not swallow cancellations. Exception is caught in try-catch. RuntimeException is thrown in main coroutine.