Skip to content
Tutorials Center
My learning

Topics

Lesson 58 of 132 ยท Error Handling

Result and Recoverable Errors

Learn how Rust handles failure with Result<T, E>: matching Ok and Err, unwrap_or, map, map_err, and_then, ok_or, early returns and a strategy.

Some things go wrong in ordinary, expected ways. A user types "banana" where a number belongs. A file is missing. A network peer hangs up. None of these are bugs in your program, and none of them should crash it. In the previous lesson you saw panics, which are for situations where the program cannot sensibly continue. For everything else Rust has a different tool: the Result type.

Rust has no exceptions. A function that can fail says so in its return type, and the caller must deal with that, because the success value is locked inside a wrapper until it has been checked. That one design decision removes a whole class of bugs: you cannot forget that parse can fail, because the compiler will not let you use the number until you have decided what to do about the failure. This lesson covers the type itself, the everyday methods on it, converting between Result and Option, and a practical way to choose between the options. The ? operator in the next lesson then removes most of the boilerplate.

What a Result is

Result is a plain enum with two variants, defined in the standard library like this:

Rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

T is the type of the success value and E is the type of the error value. Ok(42) is a Result<i32, E> for some E; Err("bad") is a Result<T, &str> for some T. Both Ok and Err are in the prelude, so you never import them.

The standard library is full of functions that return Result. str::parse::<i32>() returns Result<i32, ParseIntError>. File::open returns Result<File, io::Error>. Your own functions will return it too. The standard way to look inside is match, which forces you to handle both cases:

Rust Matching on a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each parse call yields either Ok(number) or Err(error). The error is a ParseIntError, and printing it with {} gives a readable message that depends on what went wrong: an empty string, a wrong character, or a value that does not fit the type. Notice that the last input is a perfectly valid integer that is simply too large for i32. That is also an Err, not a crash and not silent wrap-around.

Result is marked #[must_use]. If you call a function that returns one and ignore the value completely, rustc warns that the Result must be used. That is a deliberate safety net: a silently dropped error is almost always a bug.

You cannot use the value without checking

A Result<i32, _> is not an i32. The types are different, so the compiler refuses to treat one as the other.

Rust Forgetting that parse can fail (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

rustc reports error[E0308]: mismatched types, pointing at the call and explaining that it expected i32 but found Result<i32, ParseIntError>. The help note suggests .expect(...). The fix is to decide what failure means here. If it cannot happen in this program, expect documents that assumption and panics with your message if you are wrong. If it can happen, handle it. The rest of this lesson is about the second choice.

Quick extraction: unwrap, expect and the safe defaults

The shortest way to get at the value is unwrap, which returns the success value or panics. expect("message") does the same with your own panic message. Both are fine in tiny demos, in tests and for conditions you have already proven impossible, but they turn a recoverable error into a crash, so keep them out of code that handles real input.

When a sensible fallback exists, use one of the non-panicking relatives:

  • unwrap_or(value) returns the success value or the given default. The default is built eagerly, even when it is not needed.
  • unwrap_or_else(|error| ...) runs a closure only on failure, so use it when the default is expensive or depends on the error.
  • unwrap_or_default() returns T::default() on failure: 0 for numbers, an empty String, an empty Vec.
Rust Falling back to defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The closure passed to unwrap_or_else receives the error value, which is why it can log it or choose a default based on it. In the success cases (a and e) it is never called.

Transforming results without unpacking them

Often you want to apply a function to the success value and keep passing the Result along. map does that: it transforms the Ok value and leaves an Err untouched. Its mirror is map_err, which transforms the error and leaves Ok alone. map_err is how you attach context or convert one error type into another.

and_then is the one to reach for when the next step is itself fallible. It takes a closure that returns a Result and flattens the result, so you do not end up with Result<Result<_, _>, _>.

Rust map, map_err and and_then

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at what map_err does in parse_port. The original error type is ParseIntError, which says nothing about which input was wrong. The closure builds a String that includes the offending text, and from then on the function's error type is String. Later lessons replace that String with a proper enum (custom error types), but the shape of the code stays the same.

Looking at a Result without consuming it

Sometimes you only want to ask a question. is_ok() and is_err() return a bool. is_ok_and(|v| ...) and is_err_and(|e| ...) test the inner value with a closure. For branching and binding at once, if let and let ... else work on Result exactly as they do on Option:

Rust
if let Ok(n) = "12".parse::<i32>() {
    println!("got {n}");
}

let Ok(n) = "12".parse::<i32>() else {
    return;
};

let ... else is useful when the failure case needs an early exit and the rest of the function wants the unwrapped value in scope, not nested one level deeper.

Early returns the long way

Before learning the ? operator it is worth writing error propagation by hand once, because ? is simply shorthand for what you are about to see. Suppose you want to add two numbers read from text. Each parse can fail, and the failure should be reported to the caller instead of handled here:

Rust Propagating errors with match and return

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The pattern is always the same: on Ok, take the value and carry on; on Err, return the error from the whole function. It is correct but noisy, and the noise grows with every fallible call. The ? operator replaces each of those six-line match blocks with a single character.

Converting between Option and Result

Option and Result are close cousins: both carry either a value or an absence of one, and Result adds a reason. Converting between them is a daily task.

From To Method
Option<T> Result<T, E> ok_or(err) or ok_or_else(|| err)
Result<T, E> Option<T> ok() (drops the error) or err() (drops the value)
Option<Result<T, E>> Result<Option<T>, E> transpose()

ok_or is how you turn "not found" into a proper error. As with unwrap_or, prefer ok_or_else when building the error costs something, such as formatting a String.

Rust Converting between Option and Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The filter_map(... .ok()) idiom silently skips bad items. That is the right choice when bad lines are noise, and the wrong one when you need to tell the user what was wrong; the iterator patterns lesson shows how to collect into a Result instead so the first error stops the whole job.

Results and the rest of the language

Because Result is an ordinary enum, everything you know about enums applies. You can pattern match with guards, nest patterns (Ok(Some(n))), and store results in collections. A few handy details:

  • Result<(), E> is the standard type for "this can fail but returns nothing useful". The success value is the unit type (), written Ok(()).
  • A Result<T, E> is the same size as the larger of its parts plus a tag, and Option-like niche optimizations apply, so returning one in a hot loop is cheap.
  • Err does not have to hold a string. It can hold an enum, a struct, a number or a boxed trait object, and the caller can match on it. This is what makes Rust errors precise.
  • Type aliases shorten signatures that repeat the error type: type Result<T> = std::result::Result<T, MyError>; is common in libraries. The std::io module does exactly this with io::Result<T>.

Choosing a strategy

When a function can fail, you have four honest choices. Pick the one that matches who can do something about the failure.

  1. Recover here. Use a default (unwrap_or), retry, or try another source. Do this when the current function knows a reasonable alternative.
  2. Return it. Make your function return a Result and let the caller decide. This is the right default for library code and for most helper functions.
  3. Convert and return it. Use map_err to add context or to translate into your own error type, then return. This is what error design is about.
  4. Crash. Use expect or panic! when the failure means the program itself is wrong, not the input. Always write a message that explains the broken assumption.

A good rule of thumb: errors caused by the outside world (input, files, networks) are Results; errors caused by your own logic (an index you computed wrongly, an invariant you promised) are panics.

A function that returns Result is a promise to the caller, and changing Ok(T) to Result<T, E> later breaks every call site. Think about failure when you design the signature, not afterwards.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does "abc".parse::<i32>() return?

    parse returns Result<i32, ParseIntError>; invalid text gives an Err and never panics unless you call unwrap on it.
  2. 2. Which method transforms the error inside an Err and leaves an Ok unchanged?

    map changes the Ok value, map_err changes the Err value, and and_then chains another fallible step. unwrap_or_else leaves the Result world.
  3. 3. When is unwrap_or_else(|_| compute()) better than unwrap_or(compute())?

    unwrap_or(compute()) evaluates compute() before the call, even when the result is Ok. The closure version runs it only when needed.
  4. 4. How do you turn an Option<T> into a Result<T, String> with a message when it is None?

    ok_or and ok_or_else attach an error to a None. ok() goes the other way, from Result to Option.
  5. 5. Which situation is best handled by returning a Result rather than panicking?

    Bad input from the outside world is expected and recoverable, so it belongs in a Result. Logic errors in your own code are panics.

Summary

  • Result<T, E> is an enum with Ok(T) and Err(E). Functions that can fail return it, and the compiler makes callers deal with it.
  • match, if let and let ... else take a Result apart; unwrap and expect panic on Err, so keep them for impossible cases.
  • unwrap_or, unwrap_or_else and unwrap_or_default supply fallbacks; prefer the closure form when the fallback is costly.
  • map, map_err and and_then transform and chain results without unpacking them.
  • ok_or / ok_or_else turn an Option into a Result; ok() turns a Result into an Option and drops the error.
  • Choose deliberately: recover, return, convert and return, or crash. External failures are Results, broken assumptions are panics.

Next: The ? Operator