Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Errors, Panics and Process

Error handling in Rust

Overview of error handling in Rust: when to use Option, Result or panic, how the ? operator propagates errors, and how to choose error types.

Rust has no exceptions. A function that can fail says so in its return type, and the caller must deal with it before using the value. There are three tools, and choosing between them is most of the skill: Option<T> for "there may be nothing here", Result<T, E> for "this operation can fail, and here is why", and panic! for "the program has a bug or an unrecoverable state".

The rule of thumb is simple. If failure is a normal outcome (a missing map key, a malformed number typed by a user, a file that does not exist), return a value. If failure means the code itself is wrong (an index you proved was in range is not), panic. Libraries should almost never panic on bad input; applications may panic in main when they cannot continue.

Rust
fn first_even(v: &[i32]) -> Option<i32> {
    v.iter().copied().find(|n| n % 2 == 0)
}

fn parse_age(s: &str) -> Result<u8, std::num::ParseIntError> {
    s.trim().parse()
}

Try it

Rust Option, Result and ? together

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.

Rust Choosing how to react to an error

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 decision guide

Situation Use
A lookup that may find nothing Option<T>
An operation that can fail for reasons the caller may want to know Result<T, E>
A broken invariant, an impossible state, an index you already checked panic!, unreachable!, assert!
A quick script, a test, an example unwrap() or expect("why")
A function in an application that can fail in many ways Result<T, Box<dyn Error>>
A library function Result<T, YourError> with a dedicated error type

Working with errors

  • Propagate with ?. On Err(e) it returns early from the function, converting e into the function's error type with From::from. On None in an Option-returning function it returns None.
  • Transform with map, map_err, and_then, ok_or and ok_or_else instead of nested match blocks when the logic is short.
  • Recover with unwrap_or, unwrap_or_else, unwrap_or_default or or_else.
  • Collect many results at once: an iterator of Result<T, E> collects into Result<Vec<T>, E> and stops at the first error.
  • Report at the top of the program: main can return Result<(), E>; an Err is printed with Debug and the exit code becomes 1.

Usage notes

  • unwrap() and expect() turn an error into a panic. expect("message") is better because the message tells the reader what you assumed.
  • A custom error enum, Display and From give callers precise matching and let ? convert automatically. See the custom error page for a complete example.
  • Box<dyn Error> is convenient in applications but throws away the concrete type for callers who need to match on it.
  • Panics are for programmer errors. They unwind by default and can be turned into aborts in Cargo.toml; they are not meant for control flow.
  • Add context as the error travels upward. A bare "No such file or directory" is much less helpful than "could not read config.toml: No such file or directory".
  • Avoid String as an error type in libraries: it cannot be matched on in a structured way, and it does not implement std::error::Error.