An exception represents a condition that interrupts normal execution so a caller can catch it, handle it, or allow it to propagate up the stack. Kotlin’s model resembles Java’s, but functions do not need declarations for the exceptions they may throw. section 2.5 section 2.6
if (percentage !in 0..100) {
throw IllegalArgumentException(
"A percentage value must be between 0 and 100: $percentage"
)
}
Throws IllegalArgumentException when a percentage falls outside the valid 0–100 range. section 2.5
Create an exception instance directly; Kotlin has no new keyword. Because throw is an expression, it can also occupy a branch where a value would otherwise be produced. A failed branch therefore prevents the expected variable from being initialized. section 2.5
Exception behavior becomes especially important in coroutine hierarchies:
- An uncaught child failure completes its parent with the same exception and propagates the failure upward. section 18.2.1
- The parent cancels sibling coroutines to avoid useless work and release their resources. section 18.2.1
- Cancellation uses CancellationException at suspension points, so broad catches can accidentally swallow cancellation and keep work running. section 15.2.4
A failing coroutine cancels its sibling
In a regular runBlocking scope, one coroutine can print heartbeat messages while another delays for one second and throws UnsupportedOperationException. The heartbeat receives cancellation, prints its termination exception, and the original failure reaches the main thread.
























