Recognize results and ignored values
#Result has Ok/Err; Option has Some/None. ? propagates an error from a compatible function. unwrap/expect extract success or panic. _ matches or ignores a value.
Fragment
Fragment inside a function.
Reference
Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
Rust docs Error handling ↗
Result has Ok/Err; Option has Some/None. ? propagates an error from a compatible function. unwrap/expect extract success or panic. _ matches or ignores a value.
Fragment
Fragment inside a function.
Result<T, E> makes success/failure part of the type. ? returns early on Err from a compatible function, with supported error conversion. It does not catch panics. Option also supports ? in compatible Option-returning functions.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
Values with Drop run cleanup when dropped; scope exit is a common trigger. std::mem::drop consumes a value to drop it earlier. Some process termination paths do not unwind/drop values, and panicking behavior depends on the panic strategy.
Fragment
Fragment: imports and type/function declarations at file scope; usage statements inside a function.
Rust's idiomatic strategy is Result<T, E>: failure is part of the return type, the compiler warns if a Result is ignored (#[must_use]), and ? propagates an Err to the caller in one character. Option<T> is the separate type for absence, which is not an error. For bugs and broken invariants there is panic!, usually through unwrap, expect or an assert, which unwinds the thread (or aborts the process if configured). Rust has no exceptions; std::io::Error exposes OS error codes through kind() and raw_os_error() rather than as a separate mechanism.
Complete program
Complete program.
Trade-offs: Result is explicit and cheap (an ordinary return value, no unwinding), and combinators make it composable, but every fallible function needs an error type and a conversion story.
In practice: return Result for anything the caller might handle, Option for "nothing there", and panic only for programming errors. Use .ok() to drop an error you truly do not care about, and expect("why this cannot fail") rather than bare unwrap when a panic is intended. For scripts and small tools, fn main() -> Result<(), Box<dyn Error>> lets ? propagate any error out of main.
? works on Option too, but only in a function that returns Option; it does not convert between Option and Result. Use ok_or or .ok() to cross over.
Libraries usually define an error enum (thiserror 2.0.21 derives the boilerplate); applications often use anyhow 1.0.104 for a single boxed error type with context.
A custom error is usually an enum with one variant per failure, each carrying the data a caller needs. Implement Display for the human-readable message and std::error::Error so it works with ?, Box<dyn Error> and error reporters; override source() to expose an underlying cause. Callers match on the variants, and the match is exhaustive. Box<dyn Error> erases the type when you only need to report; downcast_ref recovers it.
Complete program
Complete program.
In practice: one error enum per module or library boundary is the usual granularity. Keep Display lowercase and without the cause (reporters print the source chain themselves). Implement From<OtherError> for variants that wrap another error so ? converts automatically. In libraries, derive the impls with thiserror instead of writing them by hand.
thiserror 2.0.21 generates Display, Error and From impls with #[derive(Error)], #[error("...")], #[source] and #[from]; it adds nothing to your public API that hand-written impls would not.
Add #[non_exhaustive] to a public error enum if you may add variants later; downstream matches then need a wildcard arm, so adding one is not a breaking change.
Error requires Debug + Display. Derive Debug; it is what unwrap and expect print.
An error exposes its cause through std::error::Error::source(), and following source() repeatedly gives the chain. The standard library has no context wrapper, so most code uses two crates. In libraries, thiserror (2.x) derives Display and Error for an error enum, and #[source] or #[from] on a field makes it the cause. In applications, anyhow (1.x) provides anyhow::Result, which holds any error, plus .context("...") and .with_context(|| ...) to add a layer; chain() walks the causes and downcast_ref finds a concrete type such as io::Error in them.
Complete program
Complete program.
Before you use this
Not in the standard library: cargo add anyhow@1 thiserror@2 (checked with anyhow 1.0.104 and thiserror 2.0.21).
In practice: return typed errors from libraries so callers can match, and use anyhow with .context() in binaries, where errors are only reported. Keep each Display message to its own layer and let the reporter print the "caused by" lines: {:#} prints the chain on one line, {:?} on several.
Without dependencies, write the wrapper yourself: a struct with a context: String and a source: Box<dyn Error + Send + Sync>, whose Display prints only the context and whose source() returns the box. map_err(|e| ContextError { context: "load config".into(), source: Box::new(e) }) adds a layer, and std::iter::successors(Some(err), |e| e.source()) walks the chain.
If Display includes the cause and source() also returns it, reporters print the cause twice. Pick one: the convention is source().
Returning anyhow::Result from main prints the error and its causes in Debug form and exits with status 1.
Result<T, E> is an enum with Ok(T) and Err(E), and E is usually your own enum, so the error itself is a discriminated union. ? returns early with the Err (converting via From if needed). Combinators chain steps without a match: map transforms the value, and_then runs another fallible step, map_err changes the error, ok_or turns an Option into a Result, and unwrap_or_else supplies a fallback computed from the error. match on the error enum is exhaustive, so a new variant breaks every handler that forgot it.
Complete program
Complete program.
In practice: write the happy path with ?, use combinators for short pipelines, and match on the error only where you decide what to do. Derive PartialEq on error enums so tests can assert_eq! on them.
ok_or evaluates its argument eagerly; use ok_or_else(|| ...) when building the error allocates or does work.
Result is #[must_use]: dropping one without handling it is a warning. let _ = f(); silences it explicitly.
panic! signals a bug or an unrecoverable state. By default it unwinds the current thread, dropping values on the way, and prints a message through the panic hook; a panic in main ends the process with status 101. unwrap and expect panic on Err or None, and assert!, index out of bounds and integer overflow in debug builds panic too. A thread is a panic boundary: JoinHandle::join returns Err if the thread panicked. std::panic::catch_unwind stops unwinding at a boundary, for example around an FFI callback or a task in a runtime, but it is not a try/catch for errors.
Complete program
Complete program.
In practice: return Result for anything a caller could handle, and panic when continuing would be wrong. Prefer expect("reason") to unwrap in code that ships. Applications that want a crash to be immediate can set panic = "abort" in the Cargo profile, which also makes catch_unwind useless.
catch_unwind requires the closure to be UnwindSafe; wrap shared references in AssertUnwindSafe only when you have checked that a half-finished update cannot be observed.
A panic while already panicking (for example inside Drop during unwinding) aborts the process.
Panicking across an extern "C" boundary aborts; catch it with catch_unwind on the Rust side of an FFI callback.
An iterator of Result values can be collected into Result<Vec<T>, E>: it stops at the first Err and returns it, which is the fail-fast option. To gather every error, partition(Result::is_ok) splits the results into two vectors, or a fold builds both in one pass without unwrap. There is no standard multi-error type; return Vec<E> or wrap it in your own error type with a Display that lists the parts.
Complete program
Complete program.
In practice: collect into Result<Vec<_>, _> when one bad item invalidates the batch, and partition or fold when you want to process the good items and report the bad ones. For parallel tasks, join each handle (or use a JoinSet in Tokio) and push the errors into a Vec.
The collect form short-circuits: items after the first error are not processed, so side effects in the map closure stop there too.
The unwraps after partition cannot fail (each vector holds only one variant), but a fold or a plain loop with match avoids them entirely.
In Rust the boundary is usually a type: each layer has its own error enum, and a From impl translates the layer below into it, so ? performs the translation automatically. Variants callers act on (EmailTaken) are explicit; everything else is kept whole (Storage(DbError)) for logging. The top level (an HTTP handler, main) matches on the error to pick a status and a user message, and logs the detail once. Retry logic wraps the low-level call and matches the low-level error type, before translation hides it.
Complete program
Complete program.
In practice: a library's public error type is part of its API, so do not expose a dependency's error type in a variant unless you are willing to break callers when the dependency changes. A public error type also implements Display and Error (or derives them with thiserror) so its source chain can be logged. Retry only transient variants, with a capped backoff.
Ok(with_retry(...)?) is the idiom for "convert the error with From and return"; .map_err(SignupError::from) does the same without the ?.
tracing 0.1.44 records errors as structured fields at the boundary; log the error with its source chain once rather than at each layer.
Async code sleeps with tokio::time::sleep instead of thread::sleep, and the backon crate packages retry policies with jitter (the older backoff crate is unmaintained, RUSTSEC-2025-0012).