Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Rust Error Handling: Result, Option, unwrap, and the ? Operator

Errors are values. How ? converts between error types, when unwrap is honest, and the difference between absence and failure that Option erases.

~4 min readRust
#Rust#Error Handling#Syntax
3D illustration of a two-track railway where Ok and Some cars continue while Err and None divert at a question-mark switch

Quick Summary

Rust has no exceptions. A function that can fail returns Result<T, E>; a function that may find nothing returns Option<T>. Both are ordinary enums, so the compiler forces the caller to decide what to do, and #[must_use] turns an ignored result into a warning. This is the whole design: errors are values on the return path, visible in the type signature.

The ? operator is the ergonomic core. Inside a function returning Result<T, E>, expr? evaluates expr, returns Err(e) early with From::from(e) applied if it failed, and otherwise unwraps to Ok value. Because of that automatic From conversion, a function returning Box<dyn Error> or a thiserror enum composes ? over many different error types without a single explicit match.

unwrap and expect are for the cases where failure is genuinely impossible or where a panic is the correct behaviour: tests, prototypes, and constants parsed at startup. In libraries they are a red flag, because they turn a recoverable condition into a process abort. expect at least records why the invariant holds; unwrap records nothing. Panics are for bugs, Result is for the world.

Basic syntax and query signatures

rust
#[derive(Debug)] enum AppError { Io(std::io::Error), Parse(std::num::ParseIntError), Invalid(&'static str), } impl From<std::io::Error> for AppError { fn from(e: std::io::Error) -> Self { AppError::Io(e) } } impl From<std::num::ParseIntError> for AppError { fn from(e: std::num::ParseIntError) -> Self { AppError::Parse(e) } } fn read_port(path: &str) -> Result<u16, AppError> { let text = std::fs::read_to_string(path)?; // ? converts io::Error let line = text.lines().next().ok_or(AppError::Invalid("empty file"))?; let port: u16 = line.trim().parse()?; // ? converts ParseIntError if port == 0 { return Err(AppError::Invalid("port 0")); } Ok(port) }
rust
// Combinators on Result and Option let n: Option<i32> = "12".parse::<i32>().ok(); let n = n.unwrap_or(0); let n = n.unwrap_or_else(|| compute_default()); let doubled = n.map(|x| x * 2); let r: Result<i32, &str> = Ok(3); let r = r.map(|x| x + 1).map_err(|e| format!("bad: {e}")); let out = r.unwrap_or_default(); // Collecting a fallible iterator stops at the first error let nums: Result<Vec<i32>, _> = ["1", "2", "x"].iter().map(|s| s.parse::<i32>()).collect(); // ? inside main and in Option-returning functions fn main() -> Result<(), Box<dyn std::error::Error>> { let port = read_port("config.txt")?; println!("{port}"); Ok(()) }
rust
// Option as the "not found" channel fn find_user<'a>(users: &'a [User], id: u64) -> Option<&'a User> { users.iter().find(|u| u.id == id) } // ok_or_else converts Option into Result with a lazily built error let user = find_user(&users, 7).ok_or_else(|| format!("user 7 missing"))?;

Key comparison table

TypeMissing caseError caseUse when
Option<T>None—Absence is expected, not exceptional
Result<T, E>—Err(E)Operation can fail for a reason
Result<T, Box<dyn Error>>—Any errorApplications, scripts, prototypes
Result<T, MyError>—Typed enumLibraries, where callers match variants
panic!—Abort/unwindBugs, violated invariants
Option<Result<T, E>>Both possibleBoth possibleQuery that may be absent and may fail
Unwrap familyOn failureUse when
unwrap()Panics with a generic messageTests, prototypes
expect("why")Panics with your messageInvariant you can justify
unwrap_or(v)Returns vA cheap, correct default exists
unwrap_or_else(f)Calls fDefault needs computation
unwrap_or_default()Returns Default::default()T: Default and zero is sensible
ok_or(e) / ok_or_else(f)Converts Option to ResultPropagating "not found" with ?
CombinatorEffect
mapTransform the success value
map_errTransform the error value
and_thenChain a fallible operation
or_elseRecover with another fallible operation
inspectSide effect on success, value unchanged
filter (Option)Keep only values matching a predicate
transpose (Option<Result>)Flip to Result<Option<...>>

Practical edge cases and deep dives

1. ? needs a matching error type

rust
fn bad() -> Result<(), std::fmt::Error> { let n: i32 = "x".parse()?; // E0277: ParseIntError is not fmt::Error Ok(()) }

? only inserts a From conversion, so either the target error implements From<Source> or you convert explicitly with .map_err(...). In applications, Box<dyn std::error::Error + Send + Sync> sidesteps it; in libraries, a thiserror enum is the clean answer:

rust
#[derive(Debug, thiserror::Error)] enum Error { #[error("io: {0}")] Io(#[from] std::io::Error), #[error("parse: {0}")] Parse(#[from] std::num::ParseIntError), #[error("invalid config: {0}")] Invalid(String), }

The #[from] attribute generates exactly the From impl that ? needs.

2. ? in main and in closures

main may return Result<(), E> where E: Debug, which prints the error and exits with status 1. ? does not work in a closure unless the closure also returns Result:

rust
let parsed: Result<Vec<i32>, _> = items.iter().map(|s| s.parse::<i32>()).collect(); // A closure with a `?` inside must declare its own Result let run = || -> Result<(), Box<dyn std::error::Error>> { let n: i32 = "3".parse()?; println!("{n}"); Ok(()) }; run()?;

3. unwrap in a hot path turns a data error into an outage

rust
// A single malformed row kills the whole worker let n: i32 = row.value.parse().unwrap(); // Recoverable: log and skip, or propagate let n: i32 = match row.value.parse() { Ok(n) => n, Err(e) => { tracing::warn!(%e, row = row.id, "skipping malformed row"); continue; } };

Panics unwind by default; a panic inside a tokio task aborts that task, and in a program built with panic = "abort" it kills the process. Neither is a sane response to one bad row.

4. Distinguishing "not found" from "failed to look"

rust
// Option collapses two very different outcomes fn get_user(db: &Db, id: u64) -> Option<User> { /* ... */ } // Result keeps them apart fn get_user(db: &Db, id: u64) -> Result<Option<User>, DbError> { let row = db.query("select ... where id = ?", id)?; // infrastructure failure Ok(row.map(User::from)) // absence }

The callers of the second version can return 500 for Err and 404 for Ok(None). The first version has to guess, and usually guesses wrong.

5. Option combinators instead of nested match

rust
// Nested and hard to read let city = match user { Some(u) => match u.address { Some(a) => Some(a.city), None => None, }, None => None, }; // Same semantics, one chain let city = user.as_ref().and_then(|u| u.address.as_ref()).map(|a| a.city.clone()); // With a default let city = city.unwrap_or_else(|| "unknown".to_string());

and_then is the "flatMap" of the fallible world; map keeps the container, and_then flattens it. Mixing them up produces Option<Option<T>> and a second round of unwrapping.

6. Error context: the difference between debugging in 5 minutes and 5 hours

rust
use anyhow::{Context, Result}; fn load(path: &Path) -> Result<Config> { let text = std::fs::read_to_string(path) .with_context(|| format!("reading config at {}", path.display()))?; let cfg: Config = toml::from_str(&text) .with_context(|| format!("parsing config at {}", path.display()))?; Ok(cfg) }

anyhow is for applications (one opaque error type with a context chain); thiserror is for libraries (typed errors that callers can match). Using anyhow in a public library API removes the caller's ability to distinguish variants.

7. Panics, catch_unwind and the panic = "abort" switch

rust
let result = std::panic::catch_unwind(|| { risky_computation() }); match result { Ok(v) => handle(v), Err(_) => eprintln!("worker panicked"), }

catch_unwind does not work with panic = "abort", and it does not make a panic a substitute for error handling: it cannot recover from a poisoned mutex or a partially updated invariant. Use it at task boundaries (a web handler, a worker thread) to keep one failure from taking down the pool, and return Result everywhere inside.

Common mistakes and runtime errors

Error / symptomCauseFix
E0277 the ? operator can only be used ...Wrong return type of the enclosing functionReturn Result or use match
E0277 From<X> is not implemented for Y? conversion missingImplement From, or map_err
E0308 mismatched types on Ok(...)Returning a value where a Result is expectedWrap in Ok(...)
unwrap() panics in productionUnvalidated external inputHandle the error or default
#[must_use] warning ignoredResult dropped on the floorlet _ = ... only if deliberate
? in a closure fails to compileClosure does not return ResultAnnotate the closure's return type
Option<Option<T>>map where and_then was neededUse and_then
No context in the error outputBare ? on a low-level error.context(...) / with_context
catch_unwind returns Err unexpectedlypanic = "abort" profileUse unwind or redesign
Losing the original error`map_err(_
unwrap_or allocates every callEager default computationunwrap_or_else

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.