🐦 Kotlin Advanced

What is CoroutineExceptionHandler in Kotlin?

Answer

CoroutineExceptionHandler is a CoroutineContext element that catches uncaught exceptions from root coroutines (those started with launch in a scope). Install it when creating a scope or launching a coroutine: val handler = CoroutineExceptionHandler { _, e -> log(e) }. It is important to note that CoroutineExceptionHandler does NOT work with async — exceptions from async are stored in the Deferred and re-thrown when you call await(), where you should use a try-catch. Also, it does not work with child coroutines — exceptions from child coroutines propagate to the parent, not to the handler.