Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
easternkite opened this issue Mar 13, 2025 · 0 comments
Labels
docs KDoc and API reference

Comments

@easternkite
Copy link

easternkite commented Mar 13, 2025

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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs KDoc and API reference
Projects
None yet
Development

No branches or pull requests

2 participants