0
0
Kotlinprogramming~20 mins

CancellationException behavior in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
CancellationException Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output when a coroutine is cancelled with CancellationException?
Consider the following Kotlin coroutine code. What will be printed to the console?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(5) { i ->
                println("Working on $i...")
                delay(100)
            }
        } catch (e: CancellationException) {
            println("Cancelled with message: ${e.message}")
            throw e
        } finally {
            println("Finally block executed")
        }
    }
    delay(250)
    job.cancel(CancellationException("Stop now"))
    job.join()
    println("Main ends")
}
A
Working on 0...
Working on 1...
Working on 2...
Finally block executed
Main ends
B
Working on 0...
Working on 1...
Cancelled with message: Stop now
Finally block executed
Main ends
C
Working on 0...
Working on 1...
Cancelled with message: null
Finally block executed
Main ends
D
Working on 0...
Working on 1...
Exception in thread "main" java.lang.IllegalStateException
Attempts:
2 left
💡 Hint
Think about what happens when a coroutine is cancelled and how CancellationException is handled.
Predict Output
intermediate
2:00remaining
What happens if CancellationException is caught but not rethrown?
Look at this Kotlin coroutine snippet. What will be the output?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            repeat(3) { i ->
                println("Step $i")
                delay(100)
            }
        } catch (e: CancellationException) {
            println("Caught cancellation: ${e.message}")
            // Not rethrowing
        } finally {
            println("Cleanup in finally")
        }
    }
    delay(150)
    job.cancel(CancellationException("Cancelled early"))
    job.join()
    println("Done")
}
A
Step 0
Step 1
Caught cancellation: Cancelled early
Done
B
Step 0
Step 1
Step 2
Cleanup in finally
Done
C
Step 0
Step 1
Caught cancellation: Cancelled early
Cleanup in finally
Done
D
Step 0
Step 1
Exception in thread "main" java.lang.IllegalStateException
Attempts:
2 left
💡 Hint
Consider what happens if the CancellationException is caught but not rethrown in a coroutine.
Predict Output
advanced
2:00remaining
What error is thrown if a coroutine is cancelled with a non-CancellationException?
Analyze this Kotlin coroutine code. What exception will be thrown?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            delay(1000)
        } catch (e: CancellationException) {
            println("Cancelled")
            throw e
        }
    }
    delay(100)
    job.cancel(RuntimeException("Not a cancellation"))
    job.join()
}
Ajava.lang.RuntimeException: Not a cancellation
Bkotlinx.coroutines.CancellationException
Cjava.lang.IllegalStateException
DNo exception, coroutine completes normally
Attempts:
2 left
💡 Hint
What happens if you cancel a coroutine with an exception that is not a CancellationException?
🧠 Conceptual
advanced
2:00remaining
Why should CancellationException be rethrown in coroutine catch blocks?
In Kotlin coroutines, why is it important to rethrow CancellationException after catching it?
ABecause rethrowing allows the coroutine to properly cancel and propagate the cancellation signal to parent coroutines.
BBecause rethrowing automatically restarts the coroutine.
CBecause rethrowing converts the exception into a checked exception.
DBecause rethrowing prevents the coroutine from running any finally blocks.
Attempts:
2 left
💡 Hint
Think about how coroutine cancellation propagates through coroutine hierarchies.
Predict Output
expert
2:00remaining
What is the output when a coroutine's finally block throws a CancellationException?
Examine this Kotlin coroutine code. What will be printed or thrown?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        try {
            delay(100)
        } finally {
            println("In finally")
            throw CancellationException("From finally")
        }
    }
    try {
        job.join()
    } catch (e: CancellationException) {
        println("Caught in main: ${e.message}")
    }
}
ANo output, program hangs
B
In finally
Exception in thread "main" java.lang.IllegalStateException
C
In finally
No exception caught, program ends normally
D
In finally
Caught in main: From finally
Attempts:
2 left
💡 Hint
Consider how exceptions thrown in finally blocks are handled in coroutines.