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.

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
#[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)
}// 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(())
}// 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
| Type | Missing case | Error case | Use 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 error | Applications, scripts, prototypes |
Result<T, MyError> | — | Typed enum | Libraries, where callers match variants |
panic! | — | Abort/unwind | Bugs, violated invariants |
Option<Result<T, E>> | Both possible | Both possible | Query that may be absent and may fail |
| Unwrap family | On failure | Use when |
|---|---|---|
unwrap() | Panics with a generic message | Tests, prototypes |
expect("why") | Panics with your message | Invariant you can justify |
unwrap_or(v) | Returns v | A cheap, correct default exists |
unwrap_or_else(f) | Calls f | Default needs computation |
unwrap_or_default() | Returns Default::default() | T: Default and zero is sensible |
ok_or(e) / ok_or_else(f) | Converts Option to Result | Propagating "not found" with ? |
| Combinator | Effect |
|---|---|
map | Transform the success value |
map_err | Transform the error value |
and_then | Chain a fallible operation |
or_else | Recover with another fallible operation |
inspect | Side 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
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:
#[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:
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
// 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"
// 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
// 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
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
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 / symptom | Cause | Fix |
|---|---|---|
E0277 the ? operator can only be used ... | Wrong return type of the enclosing function | Return Result or use match |
E0277 From<X> is not implemented for Y | ? conversion missing | Implement From, or map_err |
E0308 mismatched types on Ok(...) | Returning a value where a Result is expected | Wrap in Ok(...) |
unwrap() panics in production | Unvalidated external input | Handle the error or default |
#[must_use] warning ignored | Result dropped on the floor | let _ = ... only if deliberate |
? in a closure fails to compile | Closure does not return Result | Annotate the closure's return type |
Option<Option<T>> | map where and_then was needed | Use and_then |
| No context in the error output | Bare ? on a low-level error | .context(...) / with_context |
catch_unwind returns Err unexpectedly | panic = "abort" profile | Use unwind or redesign |
| Losing the original error | `map_err( | _ |
unwrap_or allocates every call | Eager default computation | unwrap_or_else |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.