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

Andrea Giuliano

08/28/2020, 4:59 PM
Hi guys, I’m experimenting exception handling inside the launch, and I’ve created a very small test to do this
Copy code
@Test
    fun testingScope() = runBlocking {
        myfun1()
    }

    suspend fun myfun1() = coroutineScope {
        val handler = CoroutineExceptionHandler { _, exception ->
            println("CoroutineExceptionHandler got $exception")
        }

        launch(handler) {
            throw Exception()
        }
    }
the test is failing because the exception gets bubbled up to the runblocking although I’m using an exception handler. Doing some debugging I’ve seen that the handler is set in the right child context, but still never called. Does anybody know why?
s

sean

08/28/2020, 6:21 PM
CoroutineExceptionHandler only works when installed at the root coroutine (or direct child of a SupervisorJob) https://kotlinlang.org/docs/reference/coroutines/exception-handling.html#coroutineexceptionhandler
a

Andrea Giuliano

08/28/2020, 7:04 PM
ah! gotcha, thanks for pointing it out, didn’t know that. So in general when you are in an inner context it’s a good practice to use a try catch instead?
s

sean

08/28/2020, 11:14 PM
If I'm planning on catching an exception I catch it on the
await()
call returned from
async { }
within a
supervisorScope
otherwise, you can try catch within the coroutine itself no problem
e

Evan R.

08/31/2020, 3:10 AM
Alternatively coroutineScope rethrows exceptions from launched coroutines so you can wrap that in a try catch as well
a

Andrea Giuliano

09/03/2020, 2:55 PM
for future reference, if you use
supervisedScope
then you can inject the errorHandler and it works as expected
4 Views