Skip to content

supervisorScope does not handle exceptions from children within withContext as expected #4385

Open
@easternkite

Description

@easternkite

Describe the bug

The supervisorScope is designed to prevent child coroutine failures from propagating up and crashing the parent. However, when a child coroutine is launched within a withContext block inside a supervisorScope, the expected exception handling behavior is broken.

The withContext block, in this scenario, behaves as if it creates a new coroutine scope, isolating the child coroutine from the supervisorScope's supervision.

Expected Behavior:

When an exception occurs within a child coroutine launched inside a withContext block that resides within a supervisorScope, the supervisorScope should catch the exception and prevent it from propagating further up the hierarchy. The supervisorScope and its parent coroutines should remain active.

Actual Behavior:

Instead of being handled by the supervisorScope, the exception propagates up past the supervisorScope and crashes the parent coroutine or even the runBlocking scope. This effectively bypasses the supervisorScope's exception handling mechanism, rendering it useless in this specific scenario.

Code Example:

import kotlinx.coroutines.*

fun main() = runBlocking {
    println("start")
    supervisorScope { // SupervisorScope started
        withContext(this.coroutineContext) { // withContext creates an UndispatchedCoroutine, child of SupervisorScope
            launch { // Child coroutine of UndispatchedCoroutine
                throw Exception("Error in child coroutine")
            }
        } // withContext block ends
    } // supervisorScope block ends (exception should be handled here, but propagates to runBlocking)
    println("end") // This line is not reached
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    docsKDoc and API reference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions