Small Programs · 12 min · free lesson

Handling Failure

Result keeps expected failure in the function's type instead of turning it into a crash.

Core idea

Use Result for failure the caller can reasonably respond to.

Coming from C? NULL and errno to Option and Result covers this side by side. · Coming from Node.js? try/catch vs Result covers this side by side.

Start with the idea

A function returning Result<T, E> makes callers handle both success and failure. match is the clearest first tool because both branches stay visible. The ? operator becomes useful once a surrounding function also returns a compatible Result. panic! and expect are better reserved for broken invariants or controlled examples, not routine bad input.

Read the code

fn half(raw: &str) -> Result<i32, String> {
    let value = raw.parse::<i32>()
        .map_err(|_| "not a number".to_string())?;
    Ok(value / 2)
}

The caller chooses what an invalid number means for this program.

Practice starter

fn read(raw: &str) -> i32 {
    raw.parse().unwrap()
}

Practise this code in Playground ↗

A Result branches into Ok and Err paths; match handles each branch and question-mark can propagate an error.
Result makes success and failure explicit. match handles both; ? can return an error to the caller.

Work through it

Imagine a command that reads a port number. The user typing letters is not a broken program; it is an expected input that deserves a useful message and another attempt. Result<T, E> makes that distinction part of the function contract. Ok(value) contains the value to continue with, while Err(error) contains the reason to show, log, or transform. The caller gets to decide whether to retry, choose a default, or stop that operation.

In the example, parse::<i32>() returns a Result. map_err converts the parsing error into a message the API promises to return. The ? operator takes the number from Ok, but returns early from half on Err. It is not a general shortcut for ignoring a failure: the enclosing function must be able to return a compatible error type. Write a match first if the two paths are unfamiliar; once both branches are clear, ? keeps the successful path readable.

Avoid unwrap() on input you do not control. A panic reports a programming defect or a deliberately impossible state; it is a poor response to ordinary bad text. As a small exercise, call half("12") and half("twelve"), printing the successful answer and an actionable error. Then decide whether dividing an odd integer by two should truncate or be rejected. That is a product rule, and the function signature and tests should make the choice visible.

An error message should be useful at the boundary where it is displayed. Deep inside a reusable parser, preserve a structured error when possible; at the UI boundary, add the input context and a concrete suggestion for correction.

A recoverable error is an outcome your caller may need to handle. Result<T, E> contains either Ok(T) or Err(E), and the type makes both possibilities visible. The ? operator returns early from the current function when it sees an Err; it is concise propagation, not a way to ignore failure. The surrounding function must have a compatible return type. Use match when the current layer can make a meaningful decision, such as asking for another input or choosing a fallback.

Trace the example twice: once with valid input and once with invalid input. Mark the first operation that can fail and whether later lines run. Add a message that tells the user what to fix rather than merely printing a debug dump. Avoid unwrap() for normal bad input; reserve it for an invariant you can justify or a deliberate experiment. A good error path leaves the program in a known state and gives the next layer enough context to respond.

Try it

Return a descriptive Result for invalid input and handle it at the caller.

What success looks like: Bad text produces a normal error value, not a panic.

Check your understanding

Why is Result a better return type here?

Reveal the answer
  1. Invalid external text is an expected possibility
  2. Result parses faster
  3. Integers can only be returned inside Result

Let the caller decide how to recover instead of forcing a panic.

One more experiment

Call half("7") and half("seven") and write both results before running. Then replace the map_err line with .unwrap(); and predict what half("seven") does now.

Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Handling Failure (courseId "basics", lessonId "recoverable-errors")
Link: https://crabrix.com/learn/basics/recoverable-errors/
Goal: Use Result for failure the caller can reasonably respond to.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=basics/recoverable-errors) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.