0
0
Kotlinprogramming~30 mins

CancellationException behavior in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Print "Main program finished" after waiting for the coroutine to finish.