1 /*
2  * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3  */
4 
5 @file:Suppress("FunctionName")
6 
7 package kotlinx.coroutines
8 
9 /**
10  * Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled while it is suspending.
11  * It indicates _normal_ cancellation of a coroutine.
12  * **It is not printed to console/log by default uncaught exception handler**.
13  * See [CoroutineExceptionHandler]
14 */
15 public actual typealias CancellationException = java.util.concurrent.CancellationException
16 
17 /**
18  * Creates a cancellation exception with a specified message and [cause].
19  */
20 @Suppress("FunctionName")
CancellationExceptionnull21 public actual fun CancellationException(message: String?, cause: Throwable?) : CancellationException =
22     CancellationException(message).apply { initCause(cause) }
23 
24 /**
25  * Thrown by cancellable suspending functions if the [Job] of the coroutine is cancelled or completed
26  * without cause, or with a cause or exception that is not [CancellationException]
27  * (see [Job.getCancellationException]).
28  */
29 internal actual class JobCancellationException public actual constructor(
30     message: String,
31     cause: Throwable?,
32     @JvmField internal actual val job: Job
33 ) : CancellationException(message), CopyableThrowable<JobCancellationException> {
34 
35     init {
36         if (cause != null) initCause(cause)
37     }
38 
fillInStackTracenull39     override fun fillInStackTrace(): Throwable {
40         if (DEBUG) {
41             return super.fillInStackTrace()
42         }
43         // Prevent Android <= 6.0 bug, #1866
44         stackTrace = emptyArray()
45         /*
46          * In non-debug mode we don't want to have a stacktrace on every cancellation/close,
47          * parent job reference is enough. Stacktrace of JCE is not needed most of the time (e.g., it is not logged)
48          * and hurts performance.
49          */
50         return this
51     }
52 
createCopynull53     override fun createCopy(): JobCancellationException? {
54         if (DEBUG) {
55             return JobCancellationException(message!!, this, job)
56         }
57 
58         /*
59          * In non-debug mode we don't copy JCE for speed as it does not have the stack trace anyway.
60          */
61         return null
62     }
63 
toStringnull64     override fun toString(): String = "${super.toString()}; job=$job"
65 
66     override fun equals(other: Any?): Boolean =
67         other === this ||
68             other is JobCancellationException && other.message == message && other.job == job && other.cause == cause
69     override fun hashCode(): Int =
70         (message!!.hashCode() * 31 + job.hashCode()) * 31 + (cause?.hashCode() ?: 0)
71 }
72 
73 @Suppress("NOTHING_TO_INLINE")
74 internal actual inline fun Throwable.addSuppressedThrowable(other: Throwable) =
75     addSuppressed(other)
76