Panic & Unwrap Scenarios
Panics indicate bugs or unrecoverable states. Replace unwrap on fallible paths with ? and typed errors; reserve panics for invariant violations and tests.
Search across all documentation pages
Panics indicate bugs or unrecoverable states. Replace unwrap on fallible paths with ? and typed errors; reserve panics for invariant violations and tests.
// Before
let port: u16 = env::var("PORT").unwrap().parse().unwrap();
// After
let port: u16 = env::var("PORT").context("PORT")?.parse().context("PORT parse")?;| Site | Replace with |
|---|---|
Option::unwrap | ok_or, context, if let |
Result::unwrap | ? |
index out of bounds | get returning Option |
assert! in lib | Result or debug_assert! |
pub fn get_user(id: UserId) -> Result<User, Error> {
repo.find(id)?.ok_or(Error::NotFound(id))
}catch_unwind at FFI boundary only. panic=abort in prod changes unwinding behavior. Backtrace: RUST_BACKTRACE=1.
try_new..get(i).| Alternative | Use When | Don't Use When |
|---|---|---|
? operator | recoverable errors | truly impossible if documented |
unwrap_or_else | fallback value | error context needed |
assert! | test/invariant | user input validation |
#[should_panic] or catch_unwind for panic tests.
Print anyhow chain; set non-zero exit.
Default catches and 500; use Result for 4xx.
std::panic::set_hook for logging; careful in embedded.
abort smaller binary; no catch_unwind recovery.
rg '\.unwrap\(' and clippy unwrap_used.
deny unwrap in public paths via clippy.
ok_or maps to domain error variant.
Task panic propagates on await unless catch in task.
Add test reproducing former panic path.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026