Understanding CancellationException Behavior in Kotlin Coroutines
📖 Scenario: Imagine you are building a simple Kotlin program that uses coroutines to perform a task that might be cancelled. You want to understand how CancellationException works when a coroutine is cancelled.
🎯 Goal: Learn how to create a coroutine, cancel it, and handle CancellationException properly to see its behavior in Kotlin.
📋 What You'll Learn
Create a coroutine that runs a simple loop
Add a variable to control cancellation
Use try-catch to handle CancellationException
Print messages to show the flow of execution
💡 Why This Matters
🌍 Real World
Understanding how to cancel coroutines and handle cancellation exceptions is important when building responsive apps that can stop work early, like cancelling network requests or user actions.
💼 Career
Many Kotlin developers use coroutines for asynchronous programming. Knowing how to handle cancellation properly is essential for writing robust and efficient code.
Progress0 / 4 steps
1
Create a coroutine with a loop
Write code to launch a coroutine using GlobalScope.launch that runs a loop from 1 to 5, printing "Working on step X" where X is the loop number. Use delay(100L) inside the loop to simulate work.
Kotlin
Hint
Use GlobalScope.launch to start a coroutine and a for loop to print steps with a delay.
2
Add a job variable to control cancellation
Create a variable called job to hold the coroutine launched with GlobalScope.launch. This will allow you to cancel the coroutine later.
Kotlin
Hint
Assign the launched coroutine to a variable job so you can cancel it later.
3
Cancel the coroutine and handle CancellationException
Use job.cancel() to cancel the coroutine after the delay. Wrap the loop inside the coroutine with a try-catch block that catches CancellationException and prints "Coroutine was cancelled".
Kotlin
Hint
Call job.cancel() to stop the coroutine and catch CancellationException inside the coroutine to print a message.
4
Print final message after coroutine cancellation
Add a println statement after job.join() that prints "Main program finished" to show the program ended cleanly.
Kotlin
Hint
Print "Main program finished" after waiting for the coroutine to finish.
Practice
(1/5)
1. What is the primary purpose of CancellationException in Kotlin coroutines?
easy
A. To stop coroutines cleanly without treating it as an error
B. To indicate a syntax error in coroutine code
C. To force a coroutine to restart automatically
D. To log coroutine execution details
Solution
Step 1: Understand coroutine cancellation
CancellationException is used to stop coroutines without throwing an error that crashes the program.
Step 2: Differentiate from errors
Unlike other exceptions, CancellationException signals a normal cancellation, not a failure.
Final Answer:
To stop coroutines cleanly without treating it as an error -> Option A
A. The coroutine never starts because launch is missing parentheses
B. Calling job.cancel() without join causes a deadlock
C. It catches Exception instead of CancellationException, so cancellation is not handled properly
D. delay(1000) cannot be cancelled
Solution
Step 1: Check exception handling
The catch block catches Exception, which includes CancellationException but does not distinguish it from other exceptions.
Step 2: Understand cancellation propagation
To specifically handle cancellation without catching unrelated exceptions, catch CancellationException explicitly.
Final Answer:
It catches Exception instead of CancellationException, so cancellation is not handled properly -> Option C
Quick Check:
Catch CancellationException explicitly to handle cancellation [OK]
Hint: Catch CancellationException, not just Exception [OK]
Common Mistakes:
Assuming Exception catch handles cancellation
Thinking delay is uncancellable
Confusing cancel() with deadlock
5. You want to cancel a coroutine but still perform some cleanup code without treating cancellation as an error. Which pattern correctly uses CancellationException to achieve this?
hard
A. Avoid catching exceptions and rely on coroutine scope cancellation only
B. Use try-catch with catch (CancellationException) to handle cancellation and run cleanup in finally
C. Use a global exception handler to catch all exceptions including cancellation
D. Use try-catch with catch (Exception) and ignore finally block
Solution
Step 1: Understand cancellation handling best practice
CancellationException should be caught explicitly to avoid treating cancellation as failure.
Step 2: Use finally block for cleanup
Cleanup code belongs in finally to ensure it runs whether coroutine completes or is cancelled.
Final Answer:
Use try-catch with catch (CancellationException) to handle cancellation and run cleanup in finally -> Option B
Quick Check:
Catch CancellationException and cleanup in finally [OK]
Hint: Catch CancellationException and cleanup in finally block [OK]
Common Mistakes:
Catching only Exception hides cancellation
Skipping finally block for cleanup
Relying on global handlers for cancellation
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.