Problem
When a job is canceled, it changes its state to “Cancelling.” Then, at the first suspension point, a CancellationException
is thrown. Write a code that will catch this exception using try and catch and use the job
factory function to cancel all the coroutines:
-
In the
try
block, print the value ofi
. -
In the
catch
block, print the exception. -
After
try
andcatch
, cancel coroutines using thejob
factory function, and then print “Canceled successfully.”
Note: Adjust the delay in such a way that we get our desired output.
Restriction
The output will be available in the terminal.
Output
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
kotlinx.coroutines.JobCancellationException: Job was cancelled; ......
Canceled successfully
Get hands-on with 1400+ tech skills courses.