CodeGym /Courses /Kotlin SELF /Error contract: exceptions and “error as a value”

Error contract: exceptions and “error as a value”

Kotlin SELF
Level 40, Lesson 0
Available

1. Introduction

When we write a function, we usually think: “It takes parameters and returns a result.” But real life quickly steps in and brings gifts: “input is not a number,” “not found,” “operation is impossible,” “file didn’t open,” “state is broken.” And that’s where the grown-up part of programming starts: you need to agree on how a function reports an error.

This agreement is called an error contract: which situations are considered errors, which of them are expected, and in what form they are returned to the calling code.

The contract matters because without it code starts living “by mood.” In one place you return null, in another you throw an exception, in a third you print println("Error") and keep going as if nothing happened. This behavior is especially dangerous in large programs: the error either “hides,” or surfaces too late and in a weird place.

A useful thought to lock in: an error is not “it just crashed”. An error is a situation where a function cannot fulfill the promise of its contract.

2. The main ways to signal an error

When you choose an error-handling strategy, you have two main tools: exceptions and error as a value.

Exception

An exception interrupts the normal execution flow: “I can’t continue; let someone outside decide.” It’s a powerful mechanism, but it’s like a fire alarm: great when there’s actually a fire, but odd if you use it to report that you ran out of sugar.

“Error as a value”

“Error as a value” means the function returns not only “success,” but also “failure” as a regular return value. We already did this via a sealed class with Ok and Error variants: the calling code must check what came back and handle it.

It’s helpful to think of the difference like this:

flowchart TD
    A[Function call] --> B{What happened?}

    B -->|Success| C[Returned a value]
    B -->|Expected problem| D[Returned Error as a value]
    B -->|Crash or logical impossibility| E[Threw an exception]

And here’s the key: choosing between D and E is not “what’s easier to write,” but what the situation means.

3. Fail-fast checks: require(...) and check(...)

Kotlin provides very convenient tools for fail-fast behavior: require(...) and check(...). They look similar, but differ in meaning.

require(...): the problem is in the input data

A common situation: a function receives arguments, and you know in advance that some values are meaningless. For example, “percent of total” when total = 0, or “expense amount” is less than zero. This is not a normal branch of the scenario; it is an incorrect function call.

In such places, require(...) is ideal: it checks a precondition and, if it is not met, throws an exception about an invalid argument.

Mini-example:

fun percent(part: Int, total: Int): Int {
    require(total > 0) { "total must be > 0, got $total" }
    require(part >= 0) { "part must be >= 0, got $part" }
    return part * 100 / total
}

fun main() {
    println(percent(2, 5)) // 40
}

Notice the message style: we don’t write “oops,” not just “error,” but we formulate the expectation and the actual value: got .... This saves hours of debugging—especially when you forget you wrote this function and come back to it in a month (that is, tomorrow).

It’s important to understand the philosophy of require: this is not “handling an error,” it is a ban on continuing because the input does not satisfy the contract. That is, we don’t try to “somehow survive” invalid arguments—we honestly say: “you can’t do that.”

check(...): the problem is in the state

If require(...) is about “the calling code passed bad arguments,” then check(...) is about “inside the program the state is such that this should not happen.” This is closer to a bug: somewhere the logic broke an invariant.

Kotlin explicitly separates these cases: check(...) throws an exception about an invalid state.

Let’s imagine a piece of our practical project (let’s условно call it ExpenseTracker), where we have a “current open session” (for example, an active budget month). If the code tries to add an expense but no active period is selected, it’s not “the user is to blame for arguments of the addExpense(...) function,” it’s that the application state is not ready.

class Session(var activeMonth: String?)

fun addExpense(session: Session, title: String) {
    check(session.activeMonth != null) { "Active month is not selected" }
    println("Added expense '$title' for month ${session.activeMonth}") // example
}

fun main() {
    val s = Session(activeMonth = "2026-01")
    addExpense(s, "Coffee") // Added expense 'Coffee' for month 2026-01
}

If activeMonth is not selected, continuing “as if everything is fine” is dangerous. Better to fail immediately and loudly so the developer (that is, you) sees the problem in tests/debugging, rather than getting a “quietly wrong report” in production.

4. Expected errors and the Ok/Error result

Sometimes a situation is unpleasant, but expected: the user entered a non-existent command, asked to delete an expense by an id that doesn’t exist, or requested a report for a category that doesn’t exist yet.

This doesn’t look like a “crash.” It looks like a “normal branch of the application’s life”: users can make mistakes, data can be missing, and that’s not a reason to set off a fireworks show of exceptions.

In such cases it’s more convenient to return a result as an explicit value, for example:

sealed class CmdResult<out T> {
    data class Ok<T>(val value: T) : CmdResult<T>()
    data class Error(val message: String) : CmdResult<Nothing>()
}

Why is this convenient?

Because the calling code sees the contract directly in the type: the function can return an error, and you are required to handle it. It’s almost like a road sign “Caution: turn ahead”: you can ignore it, but don’t be surprised later.

Mini-example: “find an expense by id.” If it’s not found, that’s not a crash, that’s expected.

data class Expense(val id: Int, val title: String)

fun findExpense(expenses: List<Expense>, id: Int): CmdResult<Expense> {
    val found = expenses.find { it.id == id }
        ?: return CmdResult.Error("Expense not found: id=$id")
    return CmdResult.Ok(found)
}

fun main() {
    val items = listOf(Expense(1, "Coffee"))
    println(findExpense(items, 2)) // Error(message=Expense not found: id=2)
}

The important idea here: “not found” is not an exception, because absence of an element is often part of the scenario. In a console application you usually turn Error into a user-friendly message and continue the command loop.

Why null is not a universal “error”

It’s very tempting to do this: “if something goes wrong, I’ll return null.” It’s tempting because it’s quick and you don’t have to declare new types. But this approach has a cost: null says almost nothing about the reason.

null is good for the situation “there is no value” or “not found,” when the reason is not important or is obvious. For example, Map[key] returns V?, and that’s fine: “there may be no value for the key.”

But as soon as you need to distinguish reasons, null starts to hurt. Imagine two cases:

  • the user entered an empty string
  • the user entered "12a"

In both cases toIntOrNull() will return null. But for the user (and for you while debugging) it’s useful to understand the difference.

A “soft, no-reason” contract (sometimes OK):

fun parseAmountOrNull(text: String): Int? = text.toIntOrNull()

fun main() {
    println(parseAmountOrNull("12a")) // null
}

An “explicit error with message” contract (often better for CLI):

fun parseAmount(text: String): CmdResult<Int> {
    val trimmed = text.trim()
    if (trimmed.isEmpty()) return CmdResult.Error("Amount is empty")
    val n = trimmed.toIntOrNull() ?: return CmdResult.Error("Amount is not a number: '$text'")
    if (n <= 0) return CmdResult.Error("Amount must be > 0, got $n")
    return CmdResult.Ok(n)
}

Here we don’t use exceptions because the errors are expected: the user enters data by hand, and hands sometimes have a mind of their own.

5. Responsibility boundary: application layers

Now for an important architectural point—without it, the error topic turns into an argument about taste. In a large project, the boundary between exceptions and “error as a value” often совпадает with the boundary between layers.

In our course, we already mentally split the program into parts: CLI (input/output), domain (command logic), storage (persistence). And choosing an error representation is logically tied to where you are.

Look at the following table as a “team agreement” (even if the team is you and your cat):

Layer What it does Typical problems How to express it most often
CLI reads strings, prints answers “the user entered nonsense” error as a value (Ok/Error), sometimes null
Domain business rules (commands, checks) “no such expense,” “can’t delete the last item” error as a value (Ok/Error), require/check for internal guarantees
Storage files, DB, network “file didn’t open,” “no permissions,” “broken format” often exceptions, because this is I/O and environment failures

Why is storage often left with exceptions? Because “the file didn’t open” is not always an expected branch of business logic. It’s an environment failure. You still must decide what to do (inform the user, exit the program, suggest a path), but inside low-level code it’s simpler and more honest to throw an exception and handle it at the scenario boundary.

But in the domain layer it’s often more convenient to return Ok/Error, because these are the application’s “rules of the game”: the user can ask to delete a non-existent id—this is expected.

6. Practice: the remove command and its contract

Let’s assemble a small fragment that shows the contract in action. Imagine that the CLI layer has already parsed the id (as a number), and in the domain layer we perform the expense removal.

Scenario: if the id is not found, that is not an exception, but an Error. If the list is empty and we try to remove, that’s also Error. But if we are given a negative id, that looks like a bug in the code higher up the stack (CLI should have validated it), and here you can use require.

data class Expense(val id: Int, val title: String)

fun removeExpense(expenses: MutableList<Expense>, id: Int): CmdResult<Expense> {
    require(id > 0) { "id must be > 0, got $id" }

    val index = expenses.indexOfFirst { it.id == id }
    if (index == -1) return CmdResult.Error("No expense with id=$id")

    val removed = expenses.removeAt(index)
    return CmdResult.Ok(removed)
}

fun main() {
    val expenses = mutableListOf(Expense(1, "Coffee"))
    println(removeExpense(expenses, 2)) // Error(message=No expense with id=2)
}

What matters here.

An invalid argument (id <= 0) is considered a violation of the call contract and is оформлен as fail-fast via require(...). And the expected situation “id not found” is returned as Error, because it is a normal branch of the scenario.

7. How to choose an approach: practical logic

In practice, it’s convenient to make the decision not based on “I like exceptions” or “I like sealed classes,” but based on a few down-to-earth questions.

  • If the situation is expected and happens regularly (for example, the user entered an invalid command), then an exception turns into noise. You’ll have to write try/catch in every usage, and the code will start to look like the TV series “Catch Me If You Can.” For expected branches, “error as a value” is almost always a better fit.
  • If after the problem you can continue working (for example, show a message and ask to re-enter input), then “error as a value” feels more natural: you stay in the normal control flow, you just take a different branch.
  • If the situation is fatal or indicates a violated program logic, then continuing is dangerous. Here an exception (or require/check/error) is justified: it forces us not to pretend that everything is fine.
  • And finally, if you are at the boundary with the “environment” (files, network, access rights), then an exception is often more honest: it’s a failure that is hard to model as a regular branch of business logic. In such places, exceptions are usually caught at the top level of the scenario and turned into a user-friendly message.

8. Two extremes and why they are harmful

There are two extremes, and both are regularly seen in beginners.

The first extreme is “exceptions for everything.” Then any user sneeze turns into a try/catch jungle. At some point you catch Exception (because otherwise it’s impossible to live), and that becomes a universal bag where both real failures and expected input errors fall. Debugging such code usually looks like an archaeological dig: you found a stack trace, but you’re not sure whether it’s a bug or the user pressed the wrong key.

The second extreme is “no exceptions at all, only Error(message).” This is also dangerous: you can accidentally sweep under the rug a situation where the program should no longer continue (for example, a data invariant is violated). Then instead of failing honestly you get a “quiet wrong state,” and then reports will be wrong, data will be corrupted, and the user will start to suspect that a poltergeist lives in your app.

A mature approach is mixed, but consistent: at one level you choose one policy and stick to it.

What’s next

Today’s lecture is about meaning and agreements. For now, we are intentionally working with simple tools: require/check and our own Ok/Error.

In the next lectures of the day, we’ll learn to consciously write try/catch as an expression (that is, “return a value from try or from catch”) and we’ll see more standard ways to package errors into a value. Kotlin really supports a style where try returns a value, and that’s convenient when you choose the policy “on error return a default or a message.”

The foundation remains the same: first you decide what to consider an error and what it should look like to the calling code, and only then you choose syntax.

9. Common mistakes

Mistake #1: turning expected situations into exceptions.
If the user entered an unknown command, it’s not “the program broke,” it’s “the user asked for something that doesn’t exist.” When you model such situations with exceptions, code quickly becomes overgrown with try/catch, and real failures get lost among “errors-as-branches.” The cure is simple: everything that is expected in the scenario should be returned as Ok/Error and handled with a regular when.

Mistake #2: using null as a universal error.
null says “there is no value” отлично, but it barely says “why.” As a result, you are forced either to guess the reason or to print a generic “failed.” If the reason matters to the user (and in a CLI it almost always does), it’s better to return Error("a clear message") than null.

Mistake #3: applying require/check with the wrong meaning.
Sometimes beginners use require(false) just “to crash.” Formally it works, but the meaning is lost. require should express a precondition on arguments, and check an invariant of state. This makes code self-documenting: from a single line you can see who is “responsible” for correctness (the calling code or internal logic).

Mistake #4: “silencing” an error and pretending everything is fine.
The most insidious mistake is when the program continues after a problem, even though it should not. For example, you “silently” ignore deleting a non-existent id, and the user thinks the deletion happened. It’s more correct to return an Error with a message or to terminate the scenario if continuing is meaningless.

Mistake #5: mixing different contracts within one function.
When the same function sometimes throws an exception, sometimes returns Error, sometimes returns null, the calling code turns into a detective story: “what do I need to check this time?” Try to keep one clear contract per function: either it signals problems via values (Ok/Error), or it fails with an exception (and that must be justified by meaning), or it returns T? in strictly limited “not found” or “no value” cases.

1
Task
Kotlin SELF, level 40, lesson 0
Locked
Store discount
Store discount
1
Task
Kotlin SELF, level 40, lesson 0
Locked
Messenger draft
Messenger draft
1
Task
Kotlin SELF, level 40, lesson 0
Locked
Questionnaire parser
Questionnaire parser
1
Task
Kotlin SELF, level 40, lesson 0
Locked
Account lookup
Account lookup
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION