Sub topic 2
unwrap, expect, and when panicking is acceptable
This chapter assumes you know basic Rust syntax, how match works on enums, and how to build and run a project with Cargo. You should also have met Result and Option in the previous chapter. Here you will learn what unwrap and expect do, what a panic is, and when a panic is the right choice.
Recoverable and unrecoverable errors
Rust splits errors into two groups. A recoverable error is one the caller can reasonably handle, such as a missing file. These are returned as Result or Option values. An unrecoverable error is a bug or a broken assumption, such as indexing past the end of a vector. These cause a panic.
A panic prints a message and a source location, then unwinds the stack. Unwinding runs destructors as it goes. By default the program then exits with a failure status. If the panic happens in a spawned thread, only that thread ends, and the parent sees the failure when it calls join.
What unwrap and expect do
unwrap returns the value inside Ok or Some. If the value is Err or None, it panics. expect does the same but lets you supply the panic message.
fn main() {
let good: Result<i32, std::num::ParseIntError> = "42".parse::<i32>();
println!("{}", good.unwrap());
let name: Option<&str> = Some("Ferris");
println!("{}", name.expect("name should always be set"));
let bad = "forty-two".parse::<i32>();
// This line panics because the string is not a number.
let n = bad.expect("config value must be a number");
println!("{n}");
}The last call panics with a message like this:
thread 'main' panicked at src/main.rs:10:15:
config value must be a number: ParseIntError { kind: InvalidDigit }With unwrap on an Err, the message reads called Result::unwrap() on an Err value: .... That text says what happened but not why you expected success. The message from expect records your reasoning, which helps whoever reads the failure later.
When panicking is acceptable
Use a panic when continuing would be wrong and no caller could sensibly recover. These cases are the usual ones:
- Tests, examples, and prototypes. A failed
unwrapfails the test, which is what you want. In a quick prototype, it lets you skip error plumbing until the design settles. - Impossible failures. If you have already proven that the operation cannot fail,
expectdocuments the proof. - Broken invariants. If a state means the program has a bug, stopping early beats continuing with corrupt data.
Here is an example of an impossible failure. The literal is valid, so the parse cannot fail.
use std::net::IpAddr;
fn main() {
let home: IpAddr = "127.0.0.1"
.parse()
.expect("hard-coded IP address should be valid");
println!("{home}");
}A good expect message states the reason the call should succeed, not the failure itself. Write "hard-coded IP address should be valid", not "failed to parse IP".
When not to panic
Do not use unwrap on data you do not control, such as user input, file contents, or network responses. These fail in normal operation. A library that panics on bad input also takes the decision away from the application that called it. In library and application code, return a Result and let the caller choose.
Where this leads
Handling every Result with match is verbose, and calling unwrap everywhere is fragile. The ? operator, which later chapters cover, gives you a third path. It hands the error to the caller in a single character, so you keep the decision where it belongs.
Exercise
A function reads a port number from an environment variable that the user sets, then calls .parse::<u16>().unwrap() on it. Is this acceptable? What would you change?
Show answer
No. The environment variable is outside the program's control, so a bad value is a normal failure, not a bug. Return a Result from the function, or handle the error with match, so the caller can report a clear message. If a panic is truly wanted, such as in a throwaway script, use expect with a message that names the variable.
Exercise
What is the difference between unwrap and expect when the value is None? Which one is better for a value you believe cannot be None, and why?
Show answer
Both panic. unwrap uses a generic message, while expect prints the message you supply. expect is better because the message records why you believed the value was present, which speeds up debugging if that belief turns out to be wrong.