This code:
fun main() {
runBlocking {
try {
val deferred = async { throw Exception() }
deferred.await()
} catch (e: E
Though all the answers are right at there place but let me throw some more light in it that might help other users. It is documented here (Official doc) that:-
If a coroutine encounters exception other than
CancellationException
, it cancels its parent with that exception. This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for structured concurrency which do not depend on CoroutineExceptionHandler implementation. The original exception is handled by the parent (In GlobalScope) when all its children terminate.It does not make sense to install an exception handler to a coroutine that is launched in the scope of the main runBlocking, since the main coroutine is going to be always cancelled when its child completes with exception despite the installed handler.
Hope this will help.