However, I’m still confused about the `cancellatio...
# coroutines
a
However, I’m still confused about the
cancellation exception
part. If I put try-catch on the code.
Copy code
fun main() = runBlocking {
    val parentScope = CoroutineScope(SupervisorJob())
    parentScope.launch {
        try {
            println("#1")
            launch {
                try {
                    println("#3")
                    fetchDataOverNetwork()
                    println("#4")
                } catch (e: Exception) {
                    println("Child's Exception not printed")
                } finally {
                    println("Child's Finally not printed")
                }
            }
            println("#2")
        } catch (e: Exception) {
            println("Parent's Exception not printed")
        } finally {
            println("Parent's Finally is printed")
        }
    }
    delay(1_000)
    parentScope.cancel()
    delay(1_000)
    println("Bye")
}
The output is:
Copy code
#1
#2
Parent's Finally is printed
#3
Bye
Why is the exception and finally block is not executed? Even though in the documentation it says..
They check for cancellation of coroutine and throw CancellationException when cancelled.
Under what condition the
CancellationException
is thrown? Thread in Slack Conversation
m
Would you mind sharing us the fetchDataOverNetwork() method body?
a
Sure, I put the full code on the previous comment above.
Copy code
suspend fun fetchDataOverNetwork() {
    val tenSecondInMillis = 10000
    val result = URL("<https://httpstat.us/200?sleep=$tenSecondInMillis>").readText()
    println("$result")
}