Reference
- It’s easier to understand if you think of a thread’s interrupt as a job’s cancel.
- When using
runCatching
, you must write code to rethrow theCancellationException
. Kotlin does not provide a convenience method for this. - Related Issue
Reason
When a job is cancelled, it should not continue running. However, if you catch a CancellationException
, the job may continue to run, so it is recommended to rethrow it.
Problematic Code
If you do not rethrow, a job that is already cancelled may continue to run.
For example, launch { testTask() }
continues to run even after its state has changed to cancelled, so both apiCall Start
and CancellationException
are printed in sequence.
Correct Code
Therefore, if the job is finished, no more code should be executed, so you must throw a CancellationException
to end code execution.
The principle is simple. If a function throws an exception, it will not execute any further.