Thuta Learning
Kotlin
AdvancedProgrammingBeginner

Sealed Types, Exceptions & Result

KotlinLesson 2240 min

What you'll walk away with

  • Choose between an exception, a Result and a sealed type for a given failure
  • Use require, check and error and say which exception each one throws
  • Wrap risky code with runCatching and read it with getOrElse, getOrNull and fold
  • Write a sealed interface and an exhaustive when without else, and explain why leaving else out is the point
  • Define a custom exception that carries data

Explain it simply

Failure in plain language

Things go wrong: a user types 'abc' where a number belongs, a network call times out, a balance is too small. Kotlin gives you three ways to deal with that. An exception interrupts the program and jumps to the nearest catch. A Result is a value holding either the answer or the error, so the caller has to look at it. A sealed type is a closed list of outcomes that you design yourself, such as Paid, Declined or Offline.

Think of ordering at a counter. An exception is a shout of 'fire!': everything stops until someone responsible deals with it. A Result is a sealed envelope that holds either your order or an apology, and you must open it. A sealed type is a menu with a fixed set of outcomes printed on it, so the staff can never invent a new outcome without updating the menu everyone reads.

Problem → Why → Solution

The problem: a crash, a silent 0 and a Boolean that cannot say enough

A function parses a port number from user input. The first version just calls toInt(), so 'http' crashes the program with a NumberFormatException and nothing in the signature warns the caller. The second version catches everything and returns 0, so a typo quietly becomes port 0 and the real reason is lost. Later the same code base returns null on failure in one place, -1 in another and throws in a third, and every caller has to remember which convention applies.

Outcomes with more than two possibilities are worse. A payment can succeed, be declined, or fail because the network is down. Squeeze those into a Boolean and the caller can no longer tell a declined card from a dead network.

failure-by-accident.kt
fun portCrash(text: String): Int = text.toInt() // "http" throws NumberFormatException

fun portSilent(text: String): Int =
    try { text.toInt() } catch (e: Exception) { 0 }

fun pay(balance: Int, price: Int): Boolean = price <= balance

fun main() {
    println(portSilent("http")) // 0: the reason is gone
    println(pay(100, 250))      // false: declined, offline or broken? nobody knows
}

Failure belongs in the types

Failure is part of a function's contract, so it deserves a place in the types. Result makes 'this can fail' visible in the signature, and a sealed type lists every outcome by name so that the compiler can force every caller to handle each one. Exceptions remain the right tool for bugs and for situations nobody up the stack can sensibly repair.

Core concept: exceptions, Result and sealed types

An exception is thrown with throw and caught with try/catch. try is an expression: val n = try { text.toInt() } catch (e: NumberFormatException) { -1 }. Kotlin has no checked exceptions, so nothing forces a caller to catch, which is why a function signature cannot be trusted to list its failures. You create your own by extending Exception: class InsufficientFundsException(val shortBy: Int) : Exception("..."), and extra fields let the catcher react without parsing a message.

Three standard functions turn a broken assumption into an exception with a clear message. require(condition) { message } checks arguments and throws IllegalArgumentException. check(condition) { message } checks state and throws IllegalStateException. error(message) throws IllegalStateException immediately and has the return type Nothing, so it fits inside an expression such as ?: error(...). requireNotNull and checkNotNull do the same for null and then smart cast the value.

FunctionThrowsUse it for
requireIllegalArgumentExceptionthe caller passed a bad argument
checkIllegalStateExceptionthe object is in the wrong state
errorIllegalStateExceptiona branch that cannot happen, or a missing item

Result<T> is a value that holds either a success or a failure. runCatching { ... } runs a block and captures any Throwable that escapes into a Result. You then read it: getOrNull returns the value or null, getOrElse { default } computes a fallback from the error, getOrThrow rethrows, and fold(onSuccess, onFailure) handles both branches. map transforms a success and leaves a failure alone. Because a function can declare Result<Int> as its return type, the caller sees in the signature that it can fail. Use it where failure is expected and local, such as parsing user input.

A sealed interface (or sealed class) declares a closed set of subtypes, all known to the compiler because they must live in the same package and module. A when over a sealed value, used as an expression, needs no else: the compiler checks that every subtype is covered, and if you add a new one later, every such when stops compiling until you handle it. Use data class for outcomes that carry data and data object for those that do not. Thanks to smart casts, inside the is Payment.Paid branch you can use payment.receipt directly.

Three ways to say it went wrong
  1. Bug or bad input: throw an exception
  2. Expected failure: return a Result
  3. Many outcomes: use a sealed type
  4. when covers every case, no else

Ask who can fix it: if nobody nearby can, use an exception; if the direct caller can, use a Result or a sealed type.

General pattern

kotlin
require(condition) { "message" }    // IllegalArgumentException
check(condition) { "message" }      // IllegalStateException

val result: Result<T> = runCatching { riskyCode() }
result.getOrElse { error -> fallback }

sealed interface Outcome {
    data class Success(val value: T) : Outcome
    data object Failure : Outcome
}
when (outcome) { is Outcome.Success -> ...; Outcome.Failure -> ... }

require and check throw when an assumption is wrong, runCatching turns an exception into a value, a sealed interface closes the list of possible outcomes, and a when must then handle each of them.

Worked example: parsing a port and paying a bill

The program has two jobs. parsePort turns bad input into a Result, and pay returns one subtype of the sealed interface Payment. Notice that the when inside describe has no else: the compiler is checking that every case is covered.

payment.kt
sealed interface Payment {
    data class Paid(val receipt: String) : Payment
    data class Declined(val reason: String) : Payment
    data object Offline : Payment
}

fun parsePort(text: String): Result<Int> = runCatching {
    val port = text.trim().toInt()
    require(port in 1..65535) { "port $port is outside 1..65535" }
    port
}

fun pay(balance: Int, price: Int, online: Boolean): Payment = when {
    !online -> Payment.Offline
    price <= 0 -> Payment.Declined("price must be positive")
    price > balance -> Payment.Declined("short by ${price - balance}")
    else -> Payment.Paid("R-$price")
}

fun describe(payment: Payment): String = when (payment) {
    is Payment.Paid -> "paid, receipt ${payment.receipt}"
    is Payment.Declined -> "declined: ${payment.reason}"
    Payment.Offline -> "offline, try again later"
}

fun main() {
    for (text in listOf("8080", "http", "70000")) {
        val message = parsePort(text).fold(
            onSuccess = { port -> "port $port ok" },
            onFailure = { error -> "bad input '$text': ${error.message}" },
        )
        println(message)
    }
    println(parsePort("443").getOrElse { 80 })
    println(parsePort("abc").getOrElse { 80 })

    println(describe(pay(balance = 100, price = 40, online = true)))
    println(describe(pay(balance = 100, price = 250, online = true)))
    println(describe(pay(balance = 100, price = 40, online = false)))
}

Code breakdown

  1. A closed set of outcomessealed interface Payment {

    The sealed interface fixes the subtypes of Payment to exactly Paid, Declined and Offline. Nobody can add a fourth from another file, so the compiler knows every possibility.

  2. An outcome without datadata object Offline : Payment

    Offline has no data to carry, so it is a data object rather than a data class: there is one instance, and it prints with a sensible name. Paid and Declined carry a receipt and a reason in data classes.

  3. Result from runCatchingfun parsePort(text: String): Result<Int> = runCatching {

    The return type Result<Int> shows in the signature that this can fail. Any exception escaping the runCatching block is captured in the Result instead of being thrown, and on success the last expression, port, becomes the value.

  4. A precondition with a messagerequire(port in 1..65535) { "port $port is outside 1..65535" }

    require checks the range and throws IllegalArgumentException when it fails. The message in { ... } is built only when the condition is false, so it costs nothing otherwise. It comes back out of runCatching as error.message, which is why 70000 reports port 70000 is outside 1..65535.

  5. Exhaustive whenfun describe(payment: Payment): String = when (payment) {

    The when is used as an expression and lists all three of Paid, Declined and Offline, so no else is needed. Inside the is Payment.Paid branch, payment is smart cast to Paid, so payment.receipt can be used directly. Adding a new subtype makes this function stop compiling.

  6. Reading a Resultprintln(parsePort("abc").getOrElse { 80 })

    fold builds a message for both the success and the failure case. getOrElse computes a fallback when it failed, so parsePort("abc") gives 80 without any exception escaping, while parsePort("443") gives 443.

You should see
port 8080 ok
bad input 'http': For input string: "http"
bad input '70000': port 70000 is outside 1..65535
443
80
paid, receipt R-40
declined: short by 150
offline, try again later

Custom exceptions and try/catch/finally

The value of a custom exception is that it can carry data: InsufficientFundsException carries shortBy, so the catcher can react without parsing a message. catch blocks are tried from top to bottom and the first match wins, so list the specific exception first, and finally runs whether the try succeeded or a catch ran.

custom-exception.kt
class InsufficientFundsException(val shortBy: Int) :
    Exception("Not enough balance, short by $shortBy")

fun withdraw(balance: Int, amount: Int): Int {
    require(amount > 0) { "amount must be positive, got $amount" }
    if (amount > balance) throw InsufficientFundsException(amount - balance)
    return balance - amount
}

fun main() {
    for (amount in listOf(30, -5, 500)) {
        try {
            println("new balance: ${withdraw(100, amount)}")
        } catch (e: InsufficientFundsException) {
            println("refused, short by ${e.shortBy}")
        } catch (e: IllegalArgumentException) {
            println("bad request: ${e.message}")
        } finally {
            println("done with $amount")
        }
    }
}

The output is new balance: 70, done with 30, then bad request: amount must be positive, got -5, done with -5, and finally refused, short by 400 and done with 500. Notice that finally prints its line once per amount whichever path the iteration took.

require, check and error in action

The helper below runs a block and prints the class name and message of whatever exception comes out. That lets you see for yourself which exception each function throws, and what the default message is when you give none.

preconditions.kt
fun describeFailure(block: () -> Unit) {
    val error = runCatching(block).exceptionOrNull()
    println("${error?.javaClass?.simpleName}: ${error?.message}")
}

class Door(private var open: Boolean = false) {
    fun lock() {
        check(!open) { "cannot lock an open door" }
    }

    fun openIt() { open = true }
}

fun main() {
    describeFailure { require(false) { "bad argument" } }
    describeFailure { check(false) { "bad state" } }
    describeFailure { error("impossible branch") }
    describeFailure { requireNotNull(null as String?) { "name is required" } }
    describeFailure { "12x".toInt() }
    describeFailure { listOf(1).first { it > 5 } }
    describeFailure { Door().apply { openIt() }.lock() }
    describeFailure { require(false) }
    describeFailure { check(false) }
}

Among the nine output lines you will see IllegalArgumentException: bad argument, IllegalStateException: bad state, IllegalStateException: impossible branch and IllegalArgumentException: name is required, while NumberFormatException and NoSuchElementException come from the standard library itself. Door.lock gives IllegalStateException: cannot lock an open door. The last two lines show the unhelpful defaults Failed requirement. and Check failed., which is what you get when you pass no message.

Which tool for which failure

ToolBest forWatch out
Exceptionbugs, broken preconditions, failures nobody nearby can repairinvisible in the signature; no checked exceptions
Result<T>expected, local failure such as parsing or a lookup, with one kind of errorrunCatching catches Throwable, CancellationException included
Sealed typeseveral named outcomes that callers must treat differentlymore code up front; a new case touches every when

runCatching catches every Throwable, not only Exception, and inside coroutines it also catches CancellationException, which can stop cancellation from working. Keep runCatching blocks small and local, and rethrow whatever you cannot handle.

In real projects

Where these tools show up in real projects

Every service has a boundary where the outside world meets your code, and that is where these tools matter most. A repository wraps a network or database call, converts the exception into a Result or a sealed UiState, and the screen never sees a raw exception. Android view models expose states such as Loading, Ready and Failed that Compose renders with an exhaustive when, so a state added later forces every screen to deal with it. Backend handlers validate request bodies with require, map domain exceptions to HTTP status codes in one place, and hand typed outcomes to the rest of the code.

Pick one convention per layer and write it down. A common split is exceptions for bugs and broken invariants inside the domain, Result for I/O that can fail in one way, and a sealed type when callers must react differently to each outcome.

  • Parsing and validation: Result<T> from runCatching, with a require per rule, yields one error message per bad input.
  • UI state: a sealed interface of Loading, Ready and Failed turns 'what should the screen show?' into an exhaustive when.
  • Payments and orders: named outcomes such as Paid, Declined and Offline keep a declined card distinct from a dead network.

Common mistakes

Common mistakes in failure handling

Adding else to a when over a sealed type

A catch-all else compiles but switches off the exhaustiveness check: when you add a Triangle subtype later, the when quietly falls into else and returns the fallback value (0.0 in a calculation) instead of failing to compile. Without else the compiler says 'when' expression must be exhaustive. Add the 'is Triangle' branch or an 'else' branch., which catches the bug before the program runs.

Mixing up require and check, or passing no message

require is for arguments (IllegalArgumentException) and check is for state (IllegalStateException); mix them up and the catcher lands in the wrong catch. With no message the exception says only Failed requirement. or Check failed., so nobody learns what went wrong. Always pass a message lambda such as require(amount > 0) { "amount must be positive, got $amount" }.

Swallowing the failure and hiding the cause

catch (e: Exception) { return 0 }, or a runCatching result that is never read, turns a bug into wrong data: the program carries on believing port 0 is real. Catch only the exact exception you can handle, let the rest propagate, and log when you do fall back. Calling getOrThrow right after runCatching adds nothing; letting the exception fly would behave the same.

Best practices

Best practices

  • Always pass a message lambda to require and check; it is built only when the condition fails.
  • Catch the most specific exception you can handle, such as NumberFormatException, and let the others propagate.
  • Prefer a sealed interface over a sealed class when the subtypes share no state, and use data object for a single instance.
  • Convert exceptions into a Result or a sealed type once, at the boundary, and pass the typed outcome around inside the domain.

Mini challenge

Mini challenge: a login with three outcomes

Model a login check. LoginResult is a sealed interface with Welcome(user), WrongPassword(attemptsLeft) and Locked. login() throws IllegalArgumentException for a blank user name (use require) and otherwise returns a LoginResult. Separately write parseAge(text): Result<Int> that rejects anything outside 0..130, then show both kinds of result, one with an exhaustive when and the other with onSuccess and onFailure.

  • The sealed interface LoginResult has Welcome, WrongPassword and Locked (a data object)
  • login(user, password, failedBefore) uses require for a blank name and returns Locked when failedBefore >= 3
  • show(result) is an exhaustive when without else
  • parseAge uses runCatching and require, and prints "34", "-4" and "abc" through onSuccess and onFailure
login.kt
// TODO: sealed interface LoginResult: Welcome(user), WrongPassword(attemptsLeft), Locked

val passwords = mapOf("ada" to "pw-ada", "bo" to "pw-bo")

// TODO: require a non-blank user; Locked after 3 failures; Welcome when the password
// matches; otherwise WrongPassword with the attempts that are left
fun login(user: String, password: String, failedBefore: Int): LoginResult {
    TODO()
}

// TODO: wrap the parsing in runCatching and reject ages outside 0..130 with require
fun parseAge(text: String): Result<Int> {
    TODO()
}

// TODO: an exhaustive when over LoginResult, with no else branch
fun show(result: LoginResult): String {
    TODO()
}

fun main() {
    // TODO: show a successful login, a wrong password and a locked account
    // TODO: call login with a blank user inside runCatching and print the message
    // TODO: parse "34", "-4" and "abc"; print accepted or rejected for each
}

Expected: It prints welcome, ada, wrong password, 1 attempts left and account locked, then blank user -> user name is blank. The last three lines are 34 accepted as 34, -4 rejected: age -4 is not realistic and abc rejected: For input string: "abc".

Show hint

Use when { ... } as a list of conditions, with failedBefore >= 3 as the first branch. attemptsLeft can be 2 - failedBefore. For parseAge, call toInt() inside runCatching first, then check require(age in 0..130) { ... }, and chain parseAge(text).onSuccess { ... }.onFailure { ... }.

Show solution
login.kt
sealed interface LoginResult {
    data class Welcome(val user: String) : LoginResult
    data class WrongPassword(val attemptsLeft: Int) : LoginResult
    data object Locked : LoginResult
}

val passwords = mapOf("ada" to "pw-ada", "bo" to "pw-bo")

fun login(user: String, password: String, failedBefore: Int): LoginResult {
    require(user.isNotBlank()) { "user name is blank" }
    return when {
        failedBefore >= 3 -> LoginResult.Locked
        passwords[user] == password -> LoginResult.Welcome(user)
        else -> LoginResult.WrongPassword(attemptsLeft = 2 - failedBefore)
    }
}

fun parseAge(text: String): Result<Int> = runCatching {
    val age = text.trim().toInt()
    require(age in 0..130) { "age $age is not realistic" }
    age
}

fun show(result: LoginResult): String = when (result) {
    is LoginResult.Welcome -> "welcome, ${result.user}"
    is LoginResult.WrongPassword -> "wrong password, ${result.attemptsLeft} attempts left"
    LoginResult.Locked -> "account locked"
}

fun main() {
    println(show(login("ada", "pw-ada", failedBefore = 0)))
    println(show(login("ada", "oops", failedBefore = 1)))
    println(show(login("ada", "pw-ada", failedBefore = 3)))

    val blank = runCatching { login(" ", "x", 0) }
    println("blank user -> ${blank.exceptionOrNull()?.message}")

    for (text in listOf("34", "-4", "abc")) {
        parseAge(text)
            .onSuccess { println("$text accepted as $it") }
            .onFailure { println("$text rejected: ${it.message}") }
    }
}

Quick quiz 1 / 3

Which exception does check(balance >= amount) { "too low" } throw when the condition is false?

Quick quiz 2 / 3

A sealed interface Shape has Circle and Square, and you add Triangle later. A when (shape) expression handles only Circle and Square and has no else. What happens?

Quick quiz 3 / 3

What does runCatching { "12x".toInt() }.getOrElse { 0 } evaluate to?

What to remember

  • Exceptions are for bugs and broken preconditions; custom ones carry data, require throws IllegalArgumentException, and check and error throw IllegalStateException.
  • Result<T> and runCatching turn an expected failure into a value you read with getOrElse, getOrNull or fold.
  • A sealed interface closes the list of outcomes, and a when without else lets the compiler check that every case is handled.
  • Adding else to such a when can switch that check off, and swallowing an exception hides its cause.

Kotlin language guide — Kotlin

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Sealed Types, Exceptions & Result | Thuta Learning