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

Sam

11/27/2018, 10:49 PM
What am i missing here? handler is not invoked
Copy code
fun main( args : Array<String> ) {

    val handler = CoroutineExceptionHandler { _, throwable -> println( "Handled $throwable" ) }

    runBlocking(handler) {

        launch {
            println( "Handler is ${coroutineContext[CoroutineExceptionHandler]}" )
            delay( 1000)
            println( "first task" )
            throw UnsupportedOperationException()
        }

    }

}
a

Alexandre

11/27/2018, 10:59 PM
I would write it like that :
Copy code
import kotlinx.coroutines.*

fun main() = runBlocking {

    val handler = CoroutineExceptionHandler { _, throwable -> println( "Handled $throwable" ) }

    val job = GlobalScope.launch(handler) {
        println( "Handler is $handler" )
            delay( 1000)
            println( "first task" )
            throw UnsupportedOperationException()
    }
}
s

Sam

11/27/2018, 11:02 PM
yeah, handler seems to work only with GlobalScope.launch
and not with the scope from runBlocking
s

Sam

11/27/2018, 11:08 PM
so why even support handlers for launch coroutines?
g

gildor

11/28/2018, 1:57 AM
Because this is how coroutines work. exception handler works, but you cannot prevent scope from fail, or you need supervisorScope
s

Sam

11/28/2018, 1:58 AM
I was looking at the docs CoroutineExceptionHandler is invoked only on exceptions which are not expected to be handled by the user, so registering it in async builder and the like of it has no effect.
I get why it is ignored for async
but based on that documentation, shouldn't the handler be invoked for launch just like GlobalScopelaunch
4 Views