Sobes.tech
Junior — Middle

What is CancelationException and in what cases does it occur?

sobes.tech AI

Answer from AI

CancellationException is an exception in Android (and Java) that occurs when an operation or task has been canceled before its completion. It is commonly used in asynchronous operations, such as working with coroutines or cancellable tasks.

In Kotlin Coroutines, if a coroutine is canceled, a CancellationException may be thrown inside it to interrupt execution and free resources. This is normal behavior, and such an exception is not considered an error but a signal of cancellation.

Example:

val job = CoroutineScope(Dispatchers.Default).launch {
    try {
        // Long-running operation
        delay(10000)
    } catch (e: CancellationException) {
        println("Coroutine was canceled")
        throw e // it is important to rethrow the exception
    }
}

job.cancel() // cancel the coroutine

Thus, CancellationException occurs during the cancellation of asynchronous operations and serves for the proper termination of such tasks.