0
0
Kotlinprogramming~5 mins

CancellationException behavior in Kotlin

Choose your learning style9 modes available
Introduction

CancellationException helps stop a running task cleanly when you want to cancel it.

You want to stop a background task when the user leaves a screen.
You want to cancel a long-running operation if it takes too long.
You want to clean up resources when a coroutine is cancelled.
You want to handle cancellation without treating it as an error.
Syntax
Kotlin
throw CancellationException("message")

This exception is special for coroutine cancellation.

It does not show as an error but as a normal cancellation.

Examples
Throwing a CancellationException with a message.
Kotlin
throw CancellationException("Job was cancelled")
Catch CancellationException to handle cancellation gracefully.
Kotlin
try {
    // some coroutine work
} catch (e: CancellationException) {
    println("Cancelled cleanly")
}
Sample Program

This program launches a coroutine that works in steps. After some time, it cancels the coroutine with a CancellationException. The coroutine catches this exception and cleans up.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(5) { i ->
                println("Working on task $i...")
                delay(500)
            }
        } catch (e: CancellationException) {
            println("Coroutine was cancelled: " + e.message)
            throw e
        } finally {
            println("Cleanup after cancellation")
        }
    }

    delay(1100) // Let it work a bit
    println("Cancelling the job")
    job.cancel(CancellationException("User requested cancellation"))
    job.join()
    println("Done")
}
OutputSuccess
Important Notes

CancellationException is used internally by coroutines to stop work without errors.

Always handle CancellationException if you want to clean up resources.

Throwing CancellationException signals cooperative cancellation.

Summary

CancellationException stops coroutines cleanly without error.

Use it to cancel tasks and handle cleanup.

Catch it to avoid treating cancellation as a failure.