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