Complete the code to create a CoroutineExceptionHandler that prints the exception message.
val handler = CoroutineExceptionHandler { _, exception ->
println("Caught: " + [1].message)
}The exception parameter holds the caught exception, so accessing exception.message prints its message.
Complete the code to launch a coroutine with the exception handler attached.
GlobalScope.launch([1]) { throw RuntimeException("Error!") }
The handler is the CoroutineExceptionHandler instance that handles exceptions in the coroutine.
Fix the error in the CoroutineExceptionHandler usage to properly catch exceptions.
val handler = CoroutineExceptionHandler { _, [1] ->
println("Caught: " + exception.message)
}The lambda parameter must be named exception to match the usage inside the block.
Fill both blanks to create a CoroutineScope with a SupervisorJob and the exception handler.
val scope = CoroutineScope([1] + [2])
Job() instead of SupervisorJob().Combining SupervisorJob() and handler creates a scope that supervises child coroutines and handles exceptions.
Fill all three blanks to define a CoroutineExceptionHandler that logs the error, then launch a coroutine with it and a dispatcher.
val handler = CoroutineExceptionHandler { _, [1] ->
println("Error: " + [2].message)
}
GlobalScope.launch([3] + handler) {
throw IllegalStateException("Oops")
}The exception parameter is named exception in the handler, used to print the message. The coroutine is launched with Dispatchers.Default plus the handler.