Sub topic 2
unwrap, expect, and when panicking is acceptable
This chapter assumes you know what Result and Option are, you can read a match over them, and you can run a Cargo project. Here you will learn what unwrap and expect do, what a panic does to a program, and how to decide when a panic is the right choice. The next chapters build the ? operator, which replaces most uses of unwrap in real code.
What unwrap does
unwrap extracts the success value from an Option or a Result. If the value is Some(v) or Ok(v), you get v. If it is None or Err(e), the program panics.
A panic is Rust's response to a bug it cannot recover from. The current thread prints a message, runs cleanup, and then stops.
fn main() {
let name: Option<&str> = None;
println!("{}", name.unwrap());
}Running this prints a message like the following to standard error, and the process exits with status 101:
thread 'main' panicked at src/main.rs:3:25:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtraceThe message names the source file, line, and column of the unwrap call. It says nothing about why the value was None. For a Result, the message includes the error value:
fn main() {
let port: u16 = "80a".parse().unwrap();
println!("{port}");
}called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }Result::unwrap formats the error with Debug, so it only exists when E: Debug. Most standard error types satisfy this. A custom error type without #[derive(Debug)] does not, and the compiler rejects the call.
expect adds your own message
expect does the same thing as unwrap but lets you supply the panic message.
fn main() {
let port: u16 = "80a".parse().expect("PORT must be a number");
println!("{port}");
}PORT must be a number: ParseIntError { kind: InvalidDigit }For a Result, the message is your text, a colon, and the Debug form of the error. For an Option, it is only your text.
The text is easy to get wrong. Many people write what went wrong ("failed to parse"). A better habit is to state what you believed to be true, so the message reads as a broken assumption:
- Weak:
.expect("failed") - Better:
.expect("hard-coded address is valid") - Better:
.expect("config was validated at startup")
When the panic fires, a reader sees which assumption failed and can go look for the code that should have guaranteed it.
What a panic does
Knowing what happens after a panic helps you judge its cost.
- The panic message is written to standard error.
- By default, Rust unwinds the stack of the panicking thread. It walks back up through each function call and runs the
Dropimplementations of local values, which closes files and releases locks. - If the panicking thread is
main, the process exits with status 101. If it is another thread, only that thread ends, and the parent sees anErrfromJoinHandle::join.
Setting RUST_BACKTRACE=1 prints the chain of calls that led to the panic. That is usually the fastest way to find the cause.
You can change step 2 in Cargo.toml. With panic = "abort", the process ends immediately and skips unwinding. This gives smaller binaries, but Drop code does not run, and no thread can recover from a panic.
[profile.release]
panic = "abort"A panic is not an exception mechanism. std::panic::catch_unwind exists, but it is meant for boundaries such as foreign-function interfaces and thread pools. It is not a way to handle ordinary failures. Code compiled with panic = "abort" cannot catch panics at all.
Variants that do not panic
Several methods look similar to unwrap but supply a fallback instead of crashing.
| Method | On `Some` / `Ok` | On `None` / `Err` |
|---|---|---|
| `unwrap` | the value | panics |
| `expect(msg)` | the value | panics with `msg` |
| `unwrap_or(default)` | the value | `default` |
| `unwrap_or_else(f)` | the value | calls `f` (with the error, for `Result`) |
| `unwrap_or_default()` | the value | `Default::default()` |
unwrap_or evaluates its argument every time, even when it is not needed. If building the default is expensive or has side effects, use unwrap_or_else with a closure, which runs only on failure.
fn main() {
let inputs = ["8080", "oops", ""];
for s in inputs {
let port: u16 = s.parse().unwrap_or(3000);
println!("{s:?} -> {port}");
}
let count: u32 = "x".parse().unwrap_or_default();
println!("count = {count}");
let label = "x"
.parse::<u32>()
.map(|n| format!("number {n}"))
.unwrap_or_else(|e| format!("not a number ({e})"));
println!("{label}");
}There are also two mirror-image methods, unwrap_err and expect_err, which panic when a Result is Ok. They appear mostly in tests that check a function fails.
A fallback hides the failure, so it is only correct when a default value is a sensible answer. Silently replacing a mistyped port with 3000 may be fine for a demo and wrong for a deployment tool.
When panicking is acceptable
The rule of thumb is that Result is for failures the caller might reasonably handle, and a panic is for bugs, meaning situations that should be impossible if the program is correct. Four cases fit that description.
Tests, examples, and prototypes
A failed unwrap in a test fails the test, which is what you want. The panic message and line number point at the problem.
#[cfg(test)]
mod tests {
#[test]
fn parses_port() {
let port: u16 = "8080".parse().unwrap();
assert_eq!(port, 8080);
}
}In throwaway prototypes, unwrap lets you focus on the main logic. Treat each one as a marker for error handling you still owe.
Invariants the code itself guarantees
Sometimes the type system cannot see what you know. A string literal that you wrote yourself will always parse, but parse still returns a Result.
use std::net::IpAddr;
fn localhost() -> IpAddr {
"127.0.0.1".parse().expect("hard-coded address is valid")
}
fn main() {
println!("{}", localhost());
}If this ever panics, a programmer made a typo, and no caller could do anything useful with an Err. Returning a Result here would only push a meaningless error onto every caller.
Lock poisoning
Mutex::lock returns Err only when another thread panicked while holding the lock. The data may then be half-updated. Many programs treat that as unrecoverable and propagate the failure with expect.
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0u32));
let handles: Vec<_> = (0..4)
.map(|_| {
let counter = Arc::clone(&counter);
thread::spawn(move || {
*counter.lock().expect("counter mutex poisoned") += 1;
})
})
.collect();
for handle in handles {
handle.join().expect("worker thread panicked");
}
println!("total = {}", *counter.lock().expect("counter mutex poisoned"));
}Startup failures in `main`
If a program cannot read its required configuration, it often has nothing useful to do. Panicking with a clear message is acceptable, though a nicer exit message is better. Returning Result from main gives a cleaner result, and a later chapter covers it.
When it is not acceptable
Do not use unwrap or expect on values that depend on the outside world: user input, files, network responses, environment variables, or data from another service. These fail in normal operation. A library function that panics on bad input also takes the decision away from its caller, who might have recovered.
Finding unwraps in a codebase
Because unwrap is easy to write and easy to forget, Clippy (Rust's linter) offers two opt-in lints, unwrap_used and expect_used. You can enable them for a crate:
#![warn(clippy::unwrap_used)]
fn main() {
let n: i32 = "42".parse().unwrap();
println!("{n}");
}Running cargo clippy then reports every unwrap call. Teams often enable unwrap_used for production code and allow it in tests with #[allow(clippy::unwrap_used)] on the test module.
Common mistakes
- Using
unwrapbecause the compiler complained. If you added it only to make the code build, the failure is now a runtime crash. Return the error with?instead. - Writing vague
expectmessages. A message such as"error"carries no more information thanunwrap. - Using
unwrap_orwith a costly or side-effecting argument. The argument runs even on success, so useunwrap_or_else. - Using a fallback to hide real failures.
unwrap_or_defaulton a failed file read makes the program behave as if the file were empty, which can corrupt data downstream. - Assuming a panic in a worker thread stops the program. It only ends that thread unless you check the result of
join.
Exercise
The function below panics on some inputs. Rewrite its body so that it never panics, without changing its signature, and explain which case from this chapter (if any) would justify keeping the unwrap.
fn double(s: &str) -> Option<i32> {
let n: i32 = s.trim().parse().unwrap();
Some(n * 2)
}
Show answer
Replace the panic with a value-returning conversion. One option is let n: i32 = s.trim().parse().ok()?; Some(n * 2). Here .ok() turns the Result into an Option, and ? returns None early when parsing fails. The unwrap would not be justified because s is caller-supplied input that can be invalid in normal use. An unwrap would only be justified if s were a literal the code controls, or if this were a test. Note also that n * 2 can overflow for large i32 values. n.checked_mul(2) returns None instead of panicking in debug builds or wrapping in release builds.