liveBook · Manning

Exception

As explained in Kotlin in Action, 2E

Exception is the Java base class for conditions that a program may catch and handle, excluding serious errors represented by Error.

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.

How Kotlin in Action, 2E covers it

How deep it goes
Explains throwing, catching, expression use, coroutine propagation, sibling cancellation, and cancellation-catching hazards.
Examples
Demonstrates percentage validation, conditional throwing, heartbeat cancellation, and timeout loops that swallow CancellationException.
What it assumes
Assumes basic Kotlin control flow and functions while introducing exception handling from the language basics.
What you can do after
Diagnose failures by tracing propagation and write handlers that avoid swallowing coroutine cancellation.
How it connects
Connects exceptions with exception handling, Java interoperability, coroutines, structured concurrency, Job hierarchies, and cancellation.

Also explained in

Compare how 25 books explain exception →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.