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.
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
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.
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
?. OnErr(e)it returns early from the function, convertingeinto the function's error type withFrom::from. OnNonein anOption-returning function it returnsNone. - Transform with
map,map_err,and_then,ok_orandok_or_elseinstead of nestedmatchblocks when the logic is short. - Recover with
unwrap_or,unwrap_or_else,unwrap_or_defaultoror_else. - Collect many results at once: an iterator of
Result<T, E>collects intoResult<Vec<T>, E>and stops at the first error. - Report at the top of the program:
maincan returnResult<(), E>; anErris printed withDebugand the exit code becomes 1.
Usage notes
unwrap()andexpect()turn an error into a panic.expect("message")is better because the message tells the reader what you assumed.- A custom error enum,
DisplayandFromgive 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
Stringas an error type in libraries: it cannot be matched on in a structured way, and it does not implementstd::error::Error.