Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 1 | <!--- TEST_NAME ExceptionsGuideTest --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 2 | |
Prendota | b8a559d | 2018-11-30 16:24:23 +0300 | [diff] [blame] | 3 | **Table of contents** |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 4 | |
| 5 | <!--- TOC --> |
| 6 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 7 | * [Exception Handling](#exception-handling) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 8 | * [Exception propagation](#exception-propagation) |
| 9 | * [CoroutineExceptionHandler](#coroutineexceptionhandler) |
| 10 | * [Cancellation and exceptions](#cancellation-and-exceptions) |
| 11 | * [Exceptions aggregation](#exceptions-aggregation) |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 12 | * [Supervision](#supervision) |
| 13 | * [Supervision job](#supervision-job) |
| 14 | * [Supervision scope](#supervision-scope) |
| 15 | * [Exceptions in supervised coroutines](#exceptions-in-supervised-coroutines) |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 16 | |
Roman Elizarov | 660c2d7 | 2020-02-14 13:18:37 +0300 | [diff] [blame] | 17 | <!--- END --> |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 18 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 19 | ## Exception Handling |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 20 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 21 | This section covers exception handling and cancellation on exceptions. |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 22 | We already know that cancelled coroutine throws [CancellationException] in suspension points and that it |
| 23 | is ignored by the coroutines' machinery. Here we look at what happens if an exception is thrown during cancellation or multiple children of the same |
| 24 | coroutine throw an exception. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 25 | |
| 26 | ### Exception propagation |
| 27 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 28 | Coroutine builders come in two flavors: propagating exceptions automatically ([launch] and [actor]) or |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 29 | exposing them to users ([async] and [produce]). |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 30 | When these builders are used to create a _root_ coroutine, that is not a _child_ of another coroutine, |
| 31 | the former builder treat exceptions as **uncaught** exceptions, similar to Java's `Thread.uncaughtExceptionHandler`, |
| 32 | while the latter are relying on the user to consume the final |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 33 | exception, for example via [await][Deferred.await] or [receive][ReceiveChannel.receive] |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 34 | ([produce] and [receive][ReceiveChannel.receive] are covered later in [Channels](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/channels.md) section). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 35 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 36 | It can be demonstrated by a simple example that creates root coroutines using the [GlobalScope]: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 37 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 38 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 39 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 40 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 41 | import kotlinx.coroutines.* |
| 42 | |
| 43 | fun main() = runBlocking { |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 44 | val job = GlobalScope.launch { // root coroutine with launch |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 45 | println("Throwing exception from launch") |
| 46 | throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler |
| 47 | } |
| 48 | job.join() |
| 49 | println("Joined failed job") |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 50 | val deferred = GlobalScope.async { // root coroutine with async |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 51 | println("Throwing exception from async") |
| 52 | throw ArithmeticException() // Nothing is printed, relying on user to call await |
| 53 | } |
| 54 | try { |
| 55 | deferred.await() |
| 56 | println("Unreached") |
| 57 | } catch (e: ArithmeticException) { |
| 58 | println("Caught ArithmeticException") |
| 59 | } |
| 60 | } |
| 61 | ``` |
| 62 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 63 | </div> |
| 64 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 65 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-01.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 66 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 67 | The output of this code is (with [debug](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#debugging-coroutines-and-threads)): |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 68 | |
| 69 | ```text |
| 70 | Throwing exception from launch |
Roman Elizarov | 303708b | 2018-09-28 12:20:49 +0300 | [diff] [blame] | 71 | Exception in thread "DefaultDispatcher-worker-2 @coroutine#2" java.lang.IndexOutOfBoundsException |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 72 | Joined failed job |
| 73 | Throwing exception from async |
| 74 | Caught ArithmeticException |
| 75 | ``` |
| 76 | |
| 77 | <!--- TEST EXCEPTION--> |
| 78 | |
| 79 | ### CoroutineExceptionHandler |
| 80 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 81 | It is possible to customize the default behavior of printing **uncaught** exceptions to the console. |
| 82 | [CoroutineExceptionHandler] context element on a _root_ coroutine can be used as generic `catch` block for |
| 83 | this root coroutine and all its children where custom exception handling may take place. |
| 84 | It is similar to [`Thread.uncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)). |
| 85 | You cannot recover from the exception in the `CoroutineExceptionHandler`. The coroutine had already completed |
| 86 | with the corresponding exception when the handler is called. Normally, the handler is used to |
| 87 | log the exception, show some kind of error message, terminate, and/or restart the application. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 88 | |
| 89 | On JVM it is possible to redefine global exception handler for all coroutines by registering [CoroutineExceptionHandler] via |
| 90 | [`ServiceLoader`](https://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html). |
| 91 | Global exception handler is similar to |
| 92 | [`Thread.defaultUncaughtExceptionHandler`](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler)) |
| 93 | which is used when no more specific handlers are registered. |
| 94 | On Android, `uncaughtExceptionPreHandler` is installed as a global coroutine exception handler. |
| 95 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 96 | `CoroutineExceptionHandler` is invoked only on **uncaught** exceptions — exceptions that were not handled in any other way. |
| 97 | In particular, all _children_ coroutines (coroutines created in the context of another [Job]) delegate handling of |
| 98 | their exceptions to their parent coroutine, which also delegates to the parent, and so on until the root, |
| 99 | so the `CoroutineExceptionHandler` installed in their context is never used. |
| 100 | In addition to that, [async] builder always catches all exceptions and represents them in the resulting [Deferred] object, |
| 101 | so its `CoroutineExceptionHandler` has no effect either. |
| 102 | |
| 103 | > Coroutines running in supervision scope do not propagate exceptions to their parent and are |
| 104 | excluded from this rule. A further [Supervision](#supervision) section of this document gives more details. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 105 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 106 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 107 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 108 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 109 | import kotlinx.coroutines.* |
| 110 | |
| 111 | fun main() = runBlocking { |
| 112 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 113 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 114 | println("CoroutineExceptionHandler got $exception") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 115 | } |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 116 | val job = GlobalScope.launch(handler) { // root coroutine, running in GlobalScope |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 117 | throw AssertionError() |
| 118 | } |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 119 | val deferred = GlobalScope.async(handler) { // also root, but async instead of launch |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 120 | throw ArithmeticException() // Nothing will be printed, relying on user to call deferred.await() |
| 121 | } |
| 122 | joinAll(job, deferred) |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 123 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 124 | } |
| 125 | ``` |
| 126 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 127 | </div> |
| 128 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 129 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-02.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 130 | |
| 131 | The output of this code is: |
| 132 | |
| 133 | ```text |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 134 | CoroutineExceptionHandler got java.lang.AssertionError |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 135 | ``` |
| 136 | |
| 137 | <!--- TEST--> |
| 138 | |
| 139 | ### Cancellation and exceptions |
| 140 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 141 | Cancellation is closely related to exceptions. Coroutines internally use `CancellationException` for cancellation, these |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 142 | exceptions are ignored by all handlers, so they should be used only as the source of additional debug information, which can |
| 143 | be obtained by `catch` block. |
Marek Langiewicz | b6dd65c | 2019-10-18 12:10:27 +0200 | [diff] [blame] | 144 | When a coroutine is cancelled using [Job.cancel], it terminates, but it does not cancel its parent. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 145 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 146 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 147 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 148 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 149 | import kotlinx.coroutines.* |
| 150 | |
| 151 | fun main() = runBlocking { |
| 152 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 153 | val job = launch { |
| 154 | val child = launch { |
| 155 | try { |
| 156 | delay(Long.MAX_VALUE) |
| 157 | } finally { |
| 158 | println("Child is cancelled") |
| 159 | } |
| 160 | } |
| 161 | yield() |
| 162 | println("Cancelling child") |
| 163 | child.cancel() |
| 164 | child.join() |
| 165 | yield() |
| 166 | println("Parent is not cancelled") |
| 167 | } |
| 168 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 169 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 170 | } |
| 171 | ``` |
| 172 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 173 | </div> |
| 174 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 175 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-03.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 176 | |
| 177 | The output of this code is: |
| 178 | |
| 179 | ```text |
| 180 | Cancelling child |
| 181 | Child is cancelled |
| 182 | Parent is not cancelled |
| 183 | ``` |
| 184 | |
| 185 | <!--- TEST--> |
| 186 | |
andrethiele | f605b26 | 2019-10-03 12:18:37 +0200 | [diff] [blame] | 187 | If a coroutine encounters an exception other than `CancellationException`, it cancels its parent with that exception. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 188 | This behaviour cannot be overridden and is used to provide stable coroutines hierarchies for |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 189 | [structured concurrency](https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/composing-suspending-functions.md#structured-concurrency-with-async). |
| 190 | [CoroutineExceptionHandler] implementation is not used for child coroutines. |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 191 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 192 | > In these examples [CoroutineExceptionHandler] is always installed to a coroutine |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 193 | that is created in [GlobalScope]. It does not make sense to install an exception handler to a coroutine that |
| 194 | is launched in the scope of the main [runBlocking], since the main coroutine is going to be always cancelled |
| 195 | when its child completes with exception despite the installed handler. |
| 196 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 197 | The original exception is handled by the parent only when all its children terminate, |
| 198 | which is demonstrated by the following example. |
| 199 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 200 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 201 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 202 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 203 | import kotlinx.coroutines.* |
| 204 | |
| 205 | fun main() = runBlocking { |
巳月 | 55a48fb | 2018-10-31 18:27:47 +0800 | [diff] [blame] | 206 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 207 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 208 | println("CoroutineExceptionHandler got $exception") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 209 | } |
| 210 | val job = GlobalScope.launch(handler) { |
| 211 | launch { // the first child |
| 212 | try { |
| 213 | delay(Long.MAX_VALUE) |
| 214 | } finally { |
| 215 | withContext(NonCancellable) { |
| 216 | println("Children are cancelled, but exception is not handled until all children terminate") |
| 217 | delay(100) |
| 218 | println("The first child finished its non cancellable block") |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | launch { // the second child |
| 223 | delay(10) |
| 224 | println("Second child throws an exception") |
| 225 | throw ArithmeticException() |
| 226 | } |
| 227 | } |
| 228 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 229 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 230 | } |
| 231 | ``` |
| 232 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 233 | </div> |
| 234 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 235 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-04.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 236 | |
| 237 | The output of this code is: |
| 238 | |
| 239 | ```text |
| 240 | Second child throws an exception |
| 241 | Children are cancelled, but exception is not handled until all children terminate |
| 242 | The first child finished its non cancellable block |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 243 | CoroutineExceptionHandler got java.lang.ArithmeticException |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 244 | ``` |
| 245 | <!--- TEST--> |
| 246 | |
| 247 | ### Exceptions aggregation |
| 248 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 249 | When multiple children of a coroutine fail with an exception the |
| 250 | general rule is "the first exception wins", so the first exception gets handled. |
| 251 | All additional exceptions that happen after the first one are attached to the first exception as suppressed ones. |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 252 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 253 | <!--- INCLUDE |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 254 | import kotlinx.coroutines.exceptions.* |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 255 | --> |
| 256 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 257 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 258 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 259 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 260 | import kotlinx.coroutines.* |
| 261 | import java.io.* |
| 262 | |
| 263 | fun main() = runBlocking { |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 264 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 265 | println("CoroutineExceptionHandler got $exception with suppressed ${exception.suppressed.contentToString()}") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 266 | } |
| 267 | val job = GlobalScope.launch(handler) { |
| 268 | launch { |
| 269 | try { |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 270 | delay(Long.MAX_VALUE) // it gets cancelled when another sibling fails with IOException |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 271 | } finally { |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 272 | throw ArithmeticException() // the second exception |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 273 | } |
| 274 | } |
| 275 | launch { |
Roman Elizarov | 938c5e9 | 2018-09-28 16:10:09 +0300 | [diff] [blame] | 276 | delay(100) |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 277 | throw IOException() // the first exception |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 278 | } |
| 279 | delay(Long.MAX_VALUE) |
| 280 | } |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 281 | job.join() |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 282 | } |
| 283 | ``` |
| 284 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 285 | </div> |
| 286 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 287 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-05.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 288 | |
Roman Elizarov | 54617b7 | 2018-09-28 17:42:44 +0300 | [diff] [blame] | 289 | > Note: This above code will work properly only on JDK7+ that supports `suppressed` exceptions |
| 290 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 291 | The output of this code is: |
| 292 | |
| 293 | ```text |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 294 | CoroutineExceptionHandler got java.io.IOException with suppressed [java.lang.ArithmeticException] |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 295 | ``` |
| 296 | |
| 297 | <!--- TEST--> |
| 298 | |
| 299 | > Note, this mechanism currently works only on Java version 1.7+. |
| 300 | Limitation on JS and Native is temporary and will be fixed in the future. |
| 301 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 302 | Cancellation exceptions are transparent and are unwrapped by default: |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 303 | |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 304 | <div class="sample" markdown="1" theme="idea" data-min-compiler-version="1.3"> |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 305 | |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 306 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 307 | import kotlinx.coroutines.* |
| 308 | import java.io.* |
| 309 | |
| 310 | fun main() = runBlocking { |
| 311 | //sampleStart |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 312 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 313 | println("CoroutineExceptionHandler got $exception") |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 314 | } |
| 315 | val job = GlobalScope.launch(handler) { |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 316 | val inner = launch { // all this stack of coroutines will get cancelled |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 317 | launch { |
| 318 | launch { |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 319 | throw IOException() // the original exception |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 320 | } |
| 321 | } |
| 322 | } |
| 323 | try { |
| 324 | inner.join() |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 325 | } catch (e: CancellationException) { |
| 326 | println("Rethrowing CancellationException with original cause") |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 327 | throw e // cancellation exception is rethrown, yet the original IOException gets to the handler |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 328 | } |
| 329 | } |
| 330 | job.join() |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 331 | //sampleEnd |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 332 | } |
| 333 | ``` |
| 334 | |
Alexander Prendota | cbeef10 | 2018-09-27 18:42:04 +0300 | [diff] [blame] | 335 | </div> |
| 336 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 337 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-exceptions-06.kt). |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 338 | |
| 339 | The output of this code is: |
| 340 | |
| 341 | ```text |
Vsevolod Tolstopyatov | a2d8088 | 2018-09-24 19:51:49 +0300 | [diff] [blame] | 342 | Rethrowing CancellationException with original cause |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 343 | CoroutineExceptionHandler got java.io.IOException |
hadihariri | 7db5553 | 2018-09-15 10:35:08 +0200 | [diff] [blame] | 344 | ``` |
| 345 | <!--- TEST--> |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 346 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 347 | ### Supervision |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 348 | |
| 349 | As we have studied before, cancellation is a bidirectional relationship propagating through the whole |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 350 | hierarchy of coroutines. Let us take a look at the case when unidirectional cancellation is required. |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 351 | |
Aaron Stacy | 2fe443b | 2019-03-24 20:00:36 -0500 | [diff] [blame] | 352 | A good example of such a requirement is a UI component with the job defined in its scope. If any of the UI's child tasks |
| 353 | have failed, it is not always necessary to cancel (effectively kill) the whole UI component, |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 354 | but if UI component is destroyed (and its job is cancelled), then it is necessary to fail all child jobs as their results are no longer needed. |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 355 | |
| 356 | Another example is a server process that spawns several children jobs and needs to _supervise_ |
| 357 | their execution, tracking their failures and restarting just those children jobs that had failed. |
| 358 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 359 | #### Supervision job |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 360 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 361 | For these purposes [SupervisorJob][SupervisorJob()] can be used. |
| 362 | It is similar to a regular [Job][Job()] with the only exception that cancellation is propagated |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 363 | only downwards. It is easy to demonstrate with an example: |
| 364 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 365 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 366 | |
| 367 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 368 | import kotlinx.coroutines.* |
| 369 | |
| 370 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 371 | val supervisor = SupervisorJob() |
| 372 | with(CoroutineScope(coroutineContext + supervisor)) { |
Vadym O | d981966 | 2018-10-19 16:16:57 -0500 | [diff] [blame] | 373 | // launch the first child -- its exception is ignored for this example (don't do this in practice!) |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 374 | val firstChild = launch(CoroutineExceptionHandler { _, _ -> }) { |
| 375 | println("First child is failing") |
| 376 | throw AssertionError("First child is cancelled") |
| 377 | } |
| 378 | // launch the second child |
| 379 | val secondChild = launch { |
| 380 | firstChild.join() |
| 381 | // Cancellation of the first child is not propagated to the second child |
| 382 | println("First child is cancelled: ${firstChild.isCancelled}, but second one is still active") |
| 383 | try { |
| 384 | delay(Long.MAX_VALUE) |
| 385 | } finally { |
| 386 | // But cancellation of the supervisor is propagated |
| 387 | println("Second child is cancelled because supervisor is cancelled") |
| 388 | } |
| 389 | } |
| 390 | // wait until the first child fails & completes |
| 391 | firstChild.join() |
| 392 | println("Cancelling supervisor") |
| 393 | supervisor.cancel() |
| 394 | secondChild.join() |
| 395 | } |
| 396 | } |
| 397 | ``` |
| 398 | |
| 399 | </div> |
| 400 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 401 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-01.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 402 | |
| 403 | The output of this code is: |
| 404 | |
| 405 | ```text |
| 406 | First child is failing |
| 407 | First child is cancelled: true, but second one is still active |
| 408 | Cancelling supervisor |
| 409 | Second child is cancelled because supervisor is cancelled |
| 410 | ``` |
| 411 | <!--- TEST--> |
| 412 | |
| 413 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 414 | #### Supervision scope |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 415 | |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 416 | For _scoped_ concurrency [supervisorScope] can be used instead of [coroutineScope] for the same purpose. It propagates cancellation |
| 417 | in one direction only and cancels all children only if it has failed itself. It also waits for all children before completion |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 418 | just like [coroutineScope] does. |
| 419 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 420 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 421 | |
| 422 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 423 | import kotlin.coroutines.* |
| 424 | import kotlinx.coroutines.* |
| 425 | |
| 426 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 427 | try { |
| 428 | supervisorScope { |
| 429 | val child = launch { |
| 430 | try { |
| 431 | println("Child is sleeping") |
| 432 | delay(Long.MAX_VALUE) |
| 433 | } finally { |
| 434 | println("Child is cancelled") |
| 435 | } |
| 436 | } |
| 437 | // Give our child a chance to execute and print using yield |
| 438 | yield() |
| 439 | println("Throwing exception from scope") |
| 440 | throw AssertionError() |
| 441 | } |
| 442 | } catch(e: AssertionError) { |
| 443 | println("Caught assertion error") |
| 444 | } |
| 445 | } |
| 446 | ``` |
| 447 | |
| 448 | </div> |
| 449 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 450 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-02.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 451 | |
| 452 | The output of this code is: |
| 453 | |
| 454 | ```text |
| 455 | Child is sleeping |
| 456 | Throwing exception from scope |
| 457 | Child is cancelled |
| 458 | Caught assertion error |
| 459 | ``` |
| 460 | <!--- TEST--> |
| 461 | |
Roman Elizarov | 3258e1f | 2019-08-22 20:08:48 +0300 | [diff] [blame] | 462 | #### Exceptions in supervised coroutines |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 463 | |
| 464 | Another crucial difference between regular and supervisor jobs is exception handling. |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 465 | Every child should handle its exceptions by itself via exception handling mechanism. |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 466 | This difference comes from the fact that child's failure is not propagated to the parent. |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 467 | It means that coroutines launched directly inside [supervisorScope] _do_ use the [CoroutineExceptionHandler] |
| 468 | that is installed in their scope in the same way as root coroutines do |
| 469 | (see [CoroutineExceptionHandler](#coroutineexceptionhandler) section for details). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 470 | |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 471 | <div class="sample" markdown="1" theme="idea" data-highlight-only> |
| 472 | |
| 473 | ```kotlin |
Prendota | 65e6c8c | 2018-10-17 11:51:08 +0300 | [diff] [blame] | 474 | import kotlin.coroutines.* |
| 475 | import kotlinx.coroutines.* |
| 476 | |
| 477 | fun main() = runBlocking { |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 478 | val handler = CoroutineExceptionHandler { _, exception -> |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 479 | println("CoroutineExceptionHandler got $exception") |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 480 | } |
| 481 | supervisorScope { |
| 482 | val child = launch(handler) { |
| 483 | println("Child throws an exception") |
| 484 | throw AssertionError() |
| 485 | } |
| 486 | println("Scope is completing") |
| 487 | } |
| 488 | println("Scope is completed") |
| 489 | } |
| 490 | ``` |
| 491 | |
| 492 | </div> |
| 493 | |
Adam Howard | f13549a | 2020-06-02 11:17:46 +0100 | [diff] [blame^] | 494 | > You can get the full code [here](../kotlinx-coroutines-core/jvm/test/guide/example-supervision-03.kt). |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 495 | |
| 496 | The output of this code is: |
| 497 | |
| 498 | ```text |
| 499 | Scope is completing |
| 500 | Child throws an exception |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 501 | CoroutineExceptionHandler got java.lang.AssertionError |
Vsevolod Tolstopyatov | 49f25a5 | 2018-09-28 13:34:10 +0300 | [diff] [blame] | 502 | Scope is completed |
| 503 | ``` |
| 504 | <!--- TEST--> |
| 505 | |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 506 | <!--- MODULE kotlinx-coroutines-core --> |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 507 | <!--- INDEX kotlinx.coroutines --> |
| 508 | [CancellationException]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-cancellation-exception/index.html |
| 509 | [launch]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/launch.html |
| 510 | [async]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/async.html |
| 511 | [Deferred.await]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/await.html |
| 512 | [GlobalScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-global-scope/index.html |
| 513 | [CoroutineExceptionHandler]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-coroutine-exception-handler/index.html |
Roman Elizarov | 94970df | 2020-04-22 13:58:16 +0300 | [diff] [blame] | 514 | [Job]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/index.html |
| 515 | [Deferred]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html |
Roman Elizarov | 0950dfa | 2018-07-13 10:33:25 +0300 | [diff] [blame] | 516 | [Job.cancel]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job/cancel.html |
| 517 | [runBlocking]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html |
| 518 | [SupervisorJob()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-supervisor-job.html |
| 519 | [Job()]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-job.html |
| 520 | [supervisorScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/supervisor-scope.html |
| 521 | [coroutineScope]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/coroutine-scope.html |
| 522 | <!--- INDEX kotlinx.coroutines.channels --> |
| 523 | [actor]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/actor.html |
| 524 | [produce]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/produce.html |
| 525 | [ReceiveChannel.receive]: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.channels/-receive-channel/receive.html |
Roman Elizarov | 99c28aa | 2018-09-23 18:42:36 +0300 | [diff] [blame] | 526 | <!--- END --> |