https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

streetsofboston

04/29/2019, 4:05 PM
Copy code
val xHandlerParent = CoroutineExceptionHandler { c, e ->
    println("Parent Handled Crash")
}

val xHandlerLeaf = CoroutineExceptionHandler { c, e ->
    println("Leaf Handled Crash")
}

fun main() {
    CoroutineScope(xHandlerParent).launch(xHandlerLeaf) {
        delay(1000)
        throw Exception("Some Exception 1")
    }

    Thread.sleep(2000)
}
prints out
Leaf Handled Crash
. However, I expected the output to be
Parent Handled Crash
, because an exception bubbles up to the top-most parent and
CoroutineExceptionHandler
of that top-most parent should be used. If I replace
CoroutineScope(xHandlerParent). ...
with
runBlocking { ... }
, the
xHandlerLeaf
is not used, as I expected, because the top-most parent is used and that is a scoped-parent that just throws the exception up the call-stack. I’m not sure if this is a bug or if I don’t understand how exceptions are handled 🙂
y

yousefa2

04/29/2019, 4:07 PM
Your
xHandlerLeaf
handles the exception which stops it from propagating to it's parent. That's why you don't get it in the parent.
s

streetsofboston

04/29/2019, 4:08 PM
But if I do:
Copy code
fun main() {
    runBlocking{ 
        launch(xHandlerLeaf) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
    }
    Thread.sleep(2000)
}
the
xHandlerLeaf
is not used.
When I change the example to this, the
xHandlerParent
does handle the exception, as I expect:
Copy code
fun main() {
    CoroutineScope(Dispatchers.Default).launch(xHandlerParent) {
        launch(xHandlerLeaf) {
            delay(1000)
            throw Exception("Some Exception 1")
        }
    }

    Thread.sleep(2000)
}
m

Martín Ickowicz

04/29/2019, 7:25 PM
as far I know the
CoroutineExceptionHandler
consumes the exception and does not propagates it in your last example you are throwing a new exception, which is caught by the parent scope
s

streetsofboston

04/29/2019, 7:32 PM
👍 1
m

Martín Ickowicz

04/29/2019, 7:37 PM
👍
3 Views