Skip to content
Free public beta until December 4, 2026: every course is open, no card needed. After that, the first chapter of each course stays free and full access is a one-time $39 ($19 for up to 100 founding members chosen for helpful feedback). Your progress is kept. How the beta works

Recipe

Choose how a function reports failure

Use when: you're writing a function that can't always produce its answer, and need to pick its return type

Goal: a panic, a Result or an Option, chosen by who can respond to the failure

Taught in Panic or Result?

  1. 1

    Write down, in words, each way the function can fail to produce its answer.

    Example

    average(scores): the list might be empty. load_settings(path): the file might be missing or unreadable, or its text might not parse.

    Why: you can only choose a response once you know what you're responding to.

  2. 2

    For each failure, ask whether it comes from outside the code (a file, input, the network) or can only happen if the code itself is wrong.

    • only a code mistake can cause it — panic, with expect or panic! and a message saying what should have been true.
    • it comes from outside and the caller needs to know why — return Result<T, E>.
    • "no answer" is ordinary and has one obvious reason — return Option<T>.

    Why: a bug needs a person to change the code; an outside failure needs a response from whoever called.

  3. 3

    In the callers, use ? until you reach a function that knows the response, and match there.

    Why: the function that noticed the failure is rarely the one that knows what the user should see.

  4. 4

    At the top, turn what's left into a message on standard error and an exit status.

    Why: main is the only place that knows it's talking to a person or a script.

Common mistakes

  • Panicking in a library over input the caller couldn't have checked in advance.
  • Returning Result for a failure that can only be a bug, so every caller writes a match for something that never happens.
  • Returning Option when the caller needs to know which of several things went wrong.