How to stop coroutines from propagating errors to its parent?

Even if I have explicitly joined the Job before try-catch, meaning that I don’t want to propagate it any further, it still won’t help at all: Kotlin Playground: Edit, Run, Share Kotlin Code Online.

TL;DR

try {
  launch {}.join()
} catch (t: Throwable) {
  
}

, and main() will still fail because the exception is propagated.

Is there any way to do something like:

try {
  launch {}.join(propagate = False)
} catch (t: Throwable) {
  // Catch the exception and it won't fail main().
}

The behavior I want is similar to

try {
  async(Job()) {}.await()
} catch (t: Throwable) {
  // Catch the exception and it won't fail main().
}

Thanks

Put try ... catch inside launch(), not outside it. Or use supervisorScope().

1 Like

Probably you want https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/supervisor-scope.html.

1 Like