I've been having problems figuring out error handling with coroutines that I've narrowed down to this unit test with the following steps:
This is all fine. However, when I try to use the same coroutine scope to launch a new coroutine, this always completes exceptionally with the same exception.
Here is the test:
fun `when you throw an exception in a coroutine scope, is the coroutine scope dead?`() { val parentJob = Job() val coroutineScope = CoroutineScope(parentJob + Dispatchers.Default) val deferredResult = coroutineScope.async { throw IllegalStateException() } runBlocking { try { deferredResult.await() } catch (e: IllegalStateException) { println("We caught the exception. Good.") } try { coroutineScope.async { println("we can still use the scope") }.await() } catch (e: IllegalStateException) { println("Why is this same exception still being thrown?") } } }
Here is the output of the test:
We caught the exception. Good.
Why is this same exception still being thrown?
Why is this happening?
How should I deal with exceptions?
Either<Result, Exception>
? Note I'm using Kotlin 1.3
When you start a coroutine in a scope (using either async
or launch
), then a failure of a coroutine by default cancels this scope to promptly cancel all the other children. This design avoid dangling and lost exceptions.
The general advice here is:
Don't use async
/ await
unless you really need concurrency. When you design your code with suspending functions there is no much need to use async
and await
.
If you do need concurrent execution, then follow the pattern:
coroutineScope { val d1 = async { doOne() } val d2 = async { doTwo() } ... // retrieve and process results process(d1.await(), d2.await(), .... ) }
If you need to handle a failure of a concurrent operation, then put try { ... } catch { ... }
around coroutineScope { ... }
to catch a failure in any of the concurrently executing operations.
SupervisorJob
) that allow fine-grained exception handling. You can read more in the documentation https://kotlinlang.org/docs/reference/coroutines/exception-handling.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.