Another important use of the coroutine context is to define behavior for uncaught exceptions. This type of context can be created by implementing CoroutineExceptionHandler, as follows:
fun main(args: Array<String>) = runBlocking {
val handler = CoroutineExceptionHandler({ context, throwable ->
println("Error captured in $context")
println("Message: ${throwable.message}")
})
launch(handler) {
TODO("Not implemented yet!")
}
// wait for the error to happen
delay(500)
}
In this example, we are creating a CoroutineExceptionHandler that prints the information of an uncaught exception. Then we start a coroutine that will throw an exception and give the application some time to print the message.
The application will then handle the exception gracefully: