If i was intended to cancel the scope then how to ...
# coroutines
a
If i was intended to cancel the scope then how to handle/suppress
JobCancellationException
at once?
s
In general, don’t suppress it. That may break the Structured Concurrency model of Coroutine(Scope)s
a
I've done
s
CancellationExceptions are a vehicle with which a
suspend
piece of code that is currently in suspended state communicates it was cancelled. The CancellationException is thrown up from that suspended piece of code all the way to the top CoroutineScope on which the initial
launch
was called. It is a special Exception, since it won’t fail any child coroutines, it just cancels them.
If you eat CancellationExceptions (handle them but forget to re-throw them up the suspended call stack), you risk leaking coroutines.
a
@streetsofboston i dont want my application stop for that exception! If i handle it whats wrong 😒
s
Your application won’t stop for a CancellationException. It only will cancel the CoroutineScope (if it is not a supervising scope)
a
So is it ok to not catch them? Because console is printed with stack traces
s
Unless you want to log them or execute some other side-effect, don’t handle CancellationException (or any of its subclasses). You may want to handle any other exception though 🙂 Be careful to handle generic throwables/exceptions without rethrowing them, though. E.g.:
Copy code
try {
    val value = someSuspendFunction() 
} catch (t: Throwable) {
    Log.e(TAG, t)
}
The above eats any exception, including any CancellationException and it breaks the Coroutines Structured Concurrency model. If you want to ‘eat/forget’ any exception do it like this:
Copy code
try {
    val value = someSuspendFunction() 
} catch (c: CancellationException) {
    throw c
} catch (t: Throwable) {
    Log.e(TAG, t)
}