0
0
Kotlinprogramming~10 mins

CancellationException behavior in Kotlin - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - CancellationException behavior
Start Coroutine
Check for Cancellation?
NoContinue Execution
Yes
Throw CancellationException
Coroutine Cancelled
Catch CancellationException?
YesHandle Cancellation
No
Propagate Exception
This flow shows how a coroutine checks for cancellation, throws CancellationException, and how it can be caught or propagated.
Execution Sample
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
  val job = launch(Dispatchers.Default) {
    delay(100)
    println("Still running")
  }
  job.cancel()
  job.join()
  println("Done")
}
This code launches a coroutine, cancels it before delay ends, and waits for completion.
Execution Table
StepActionCoroutine StateException ThrownOutput
1Launch coroutineActiveNone
2Start delay(100)ActiveNone
3Call job.cancel()CancellingNone
4Coroutine checks cancellation during delayCancellingCancellationException
5Coroutine stops due to CancellationExceptionCancelledCancellationException
6job.join() waits for coroutine completionCancelledNone
7Print "Done"CancelledNoneDone
💡 Coroutine cancelled by CancellationException during delay, then job.join() completes and main prints "Done".
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5Final
job.isActivefalsetruefalsefalsefalse
job.isCancelledfalsefalsetruetruetrue
job.isCompletedfalsefalsefalsetruetrue
Key Moments - 2 Insights
Why does the coroutine stop even though no explicit exception handling is shown?
Because CancellationException is special in coroutines: it is thrown internally to stop the coroutine when cancelled, and it is not treated as a failure unless caught. See execution_table rows 4 and 5.
What happens if we do not call job.join() after cancelling?
Without job.join(), the main coroutine might finish before the launched coroutine fully cancels, causing unpredictable output timing. The join ensures the coroutine completes cancellation before continuing. See execution_table row 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 4, what exception is thrown inside the coroutine?
ANullPointerException
BIllegalStateException
CCancellationException
DNo exception
💡 Hint
Check the 'Exception Thrown' column at step 4 in the execution_table.
At which step does the coroutine state become 'Cancelled'?
AStep 4
BStep 5
CStep 3
DStep 7
💡 Hint
Look at the 'Coroutine State' column in the execution_table to find when it changes to 'Cancelled'.
If we remove job.join(), what is the likely effect on the output?
A"Done" might print before coroutine cancellation completes
B"Still running" will always print
CProgram will crash with exception
DNo change in output
💡 Hint
Refer to key_moments explanation about job.join() ensuring coroutine completion.
Concept Snapshot
CancellationException in Kotlin coroutines:
- Thrown internally when coroutine is cancelled
- Stops coroutine execution without failure
- Can be caught to handle cancellation
- Use job.cancel() to request cancellation
- Use job.join() to wait for coroutine to finish cancelling
Full Transcript
This visual trace shows how Kotlin coroutines handle cancellation using CancellationException. When a coroutine is cancelled, it throws CancellationException internally to stop execution. This exception is special and does not count as a failure unless caught. The example code launches a coroutine that delays for 100ms, but it is cancelled before delay ends. The coroutine throws CancellationException and stops. The main coroutine waits for cancellation to complete using job.join() before printing "Done". Variables track the coroutine state changes from active to cancelling to cancelled. Key moments clarify why the coroutine stops without explicit exception handling and why join() is important. The quiz tests understanding of when exceptions occur, state changes, and effects of removing join().