If I use the pattern of using a `Job()` as an expl...
# coroutines
s
If I use the pattern of using a
Job()
as an explicit lifecycle as mentioned here: https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#cancellation-via-explicit-job Is installing a
CoroutineExceptionHandler
the only way to handle exceptions in the lifecycle ?
g
exceptions in the lifecycle? What do you mean?
error handling depends on how you run your coroutines and which coroutine builder you use
s
In the example if it threw an exception instead of
println("Coroutine $i is done")
g
launch will throw exception, this is how launch works
so or wrap code inside of launch to try catch, or use CoroutineExceptionHandler
s
So there is no way to extract the exception from the
job
?
I think previously I had something like
Copy code
try { job.join() } catch (e: Exception) { handleException }
g
no, this is not how launch works
s
But I think that stopped working after structured concurrency
g
Job is just to control lifecycle not to get results
No it never worked like that. there is
deferred.await()
which throws exception, not
join()
Structured concurrency changed this, it’s true, but just in terms, that you can try/catch/finally exception, but if child is crashed, parent will be also cancelled to avoid leaking of other coroutines. To use old behaviour you need SupervisorJob, in this case crash of child will not cancel parent and it’s your responsibility to manage running coroutines in case of error
👍 1
s
Hmm ok. Thanks
g
If you need something like
try { job.join() }
use asinc/await instead of launch:
try { deferred.await() }
t
Beware that async/await even with try catch does cancel the parent job and SupervisorJob maybe needed in some cases depending on what you want to achieve.