https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Animesh Sahu

11/20/2019, 3:35 PM
If i was intended to cancel the scope then how to handle/suppress
JobCancellationException
at once?
s

streetsofboston

11/20/2019, 3:58 PM
In general, don’t suppress it. That may break the Structured Concurrency model of Coroutine(Scope)s
a

Animesh Sahu

11/20/2019, 3:59 PM
I've done
s

streetsofboston

11/20/2019, 4:04 PM
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

Animesh Sahu

11/20/2019, 4:07 PM
@streetsofboston i dont want my application stop for that exception! If i handle it whats wrong 😒
s

streetsofboston

11/20/2019, 4:13 PM
Your application won’t stop for a CancellationException. It only will cancel the CoroutineScope (if it is not a supervising scope)
a

Animesh Sahu

11/20/2019, 4:14 PM
So is it ok to not catch them? Because console is printed with stack traces
s

streetsofboston

11/20/2019, 4:19 PM
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)
}
4 Views