In Rust, when should code panic instead of returning a Result, and why does indexing a Vec out of bounds panic?
answer
- bug versus expected failure
- a contract the caller broke
- get returns an Option instead
- expect says why it should hold
basics
~20 sPanic when a bug has broken an invariant; return Result when failure is expected, like bad input or a lost connection. An out-of-bounds Vec index panics because it breaks the caller's contract and reading past the buffer is never allowed.
solid answer
~50 sA `Result` says failure is a normal outcome the caller must decide about: a malformed request body, a missing file, a timeout. A panic says the program reached a state its own logic calls impossible, an invariant or a function's contract was broken, so the fix is a code change, not a retry. Indexing with `v[i]` has the contract `i < v.len()`; breaking it is the caller's bug, and continuing would mean reading outside the buffer, so std panics with `index out of bounds: the len is 3 but the index is 7`. When out-of-range is a normal possibility, `v.get(i)` returns an `Option` instead. `unwrap` and `expect` turn an `Err` or `None` into a panic; keep them for invariants, tests, examples and prototypes, and give `expect` a message saying why the value *should* be there.
code
rust · 21 linesfn page_title(titles: &[String], page: usize) -> Result<&str, String> {
match titles.get(page) {
Some(t) => Ok(t),
None => Err(format!("no page {page}; there are {}", titles.len())),
}
}
fn main() {
let titles: Vec<String> = vec!["home".into(), "docs".into(), "blog".into()];
// Expected failure: a client asked for a page that does not exist.
println!("{:?}", page_title(&titles, 7));
// Invariant the compiler cannot see: the list was built non-empty above.
let first = titles.first().expect("titles should be non-empty: built from a literal");
println!("{first}");
// A bug: indexing past the end panics instead of returning an error.
let requested = 7;
println!("{}", titles[requested]);
}go deeper
Recall the split: Result for failures callers should handle, panics for bugs. Know that v[i] panics while v.get(i) returns an Option, and that expect only adds a message.
Explain contracts and invariants, why std panics on out-of-bounds access, the track_caller location in unwrap messages, and why expect messages are phrased with should.
Show where panics belong in a service: untrusted input becomes a Result at the edge, panics stay for invariants, and a stray index panic in one handler is contained and logged.
Treat unwrap and expect as a team policy question: which code may panic, how a reviewer judges an expect, and which lints enforce the rule without pushing people to hide bugs.
## Two kinds of failure Rust splits failure into two mechanisms, and choosing between them is the first error-handling decision in any function. - **`Result<T, E>`** is a value. A function returns `Err(e)` when failure is an expected outcome that the caller can sensibly react to: a parser fed malformed data, a file that does not exist, an HTTP call that was rate limited. The caller decides whether to retry, report, fall back or give up. - **A panic** is the program declaring that it hit a **bug**: some assumption, guarantee, contract or invariant was broken. Panicking stops normal execution of the current thread, because the code after this point relied on that invariant and cannot continue meaningfully. The Rust Book's guidance boils down to a test. Panicking is advisable when the code could end up in a **bad state** that is *unexpected* (not something that happens occasionally, like a user typing a bad date), when the code after this point needs to rely on not being in that state, and when there is no good way to encode the guarantee in the types. If the failure is expected, return a `Result`, even if you personally think it will be rare. Returning `Result` is the default for a function that might fail, because it keeps the decision with the caller; a panic makes the "this is unrecoverable" decision on the caller's behalf. ## Why an out-of-bounds index panics `v[i]` on a `Vec<T>` or a slice has a documented contract: `i` must be less than `len()`. Violating it is always a bug in the calling code, and the only alternative to stopping would be reading memory that does not belong to the vector, which safe Rust never allows. So the bounds check fails and std panics: `index out of bounds: the len is 3 but the index is 7` When an index may legitimately be out of range (a page number from a query string, say), you ask with **`get`**, which returns `Option<&T>`: `Some(&value)` in range, `None` outside it. There is a compile-time twist: for a fixed-size **array** indexed by a constant, rustc can prove the access always fails, and the deny-by-default `unconditional_panic` lint rejects it with `error: this operation will panic at runtime`. A `Vec` index is checked at run time instead. | Expression | Out of range or missing | Use it when | |---|---|---| | `v[i]` | panics | the index is correct by construction | | `v.get(i)` | returns `None` | out of range is a normal case | | `r.unwrap()` | panics, showing the `Err` value for a `Result` | tests, examples, prototypes | | `r.expect("… should …")` | panics with your message plus the `Err` | an invariant the compiler cannot see | | `r?` | returns the error to the caller | the caller should decide | ## unwrap and expect `Option::unwrap`, `Result::unwrap` and their `expect` counterparts convert an absent or failed value into a panic. They differ only in the message: - `"80a".parse::<u16>().unwrap()` panics with ``called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }``. - `.expect("PORT should be a number set by the deploy manifest")` panics with that text, a colon, and the same `Debug` output. std's documentation recommends phrasing `expect` messages around the word **should**: describe why you expected success, not that it failed (the panic already says that). Both methods are `#[track_caller]`, so the reported file and line are where *you* called them, not a line inside the standard library. ## What a panic does by default With the default strategy, a panic prints `thread 'main' panicked at src/main.rs:20:26:` plus the message and a hint about `RUST_BACKTRACE`, then **unwinds** the panicking thread, running `Drop` for its live values. If that thread is `main`, the process exits with status 101. The lesson on unwinding and aborting covers what happens on other threads and under the abort strategy. ## When a panic is the right call 1. **Tests**: a failed `unwrap` fails the test, which is exactly what you want. 2. **Examples and prototypes**: `unwrap` marks a spot where real handling will go later. 3. **Invariants you can see and the compiler cannot**: parsing the literal `"127.0.0.1"` cannot fail, so `expect("hardcoded IP address should be valid")` documents the reasoning. 4. **Contract violations by a caller** where continuing would be insecure or wrong, which is why std panics on out-of-bounds access. Document such panics in a `# Panics` section. Everything driven by input, I/O or the network belongs in a `Result`.
- Why does `let a = [1, 2, 3]; a[5]` fail to compile in Rust when indexing a Vec past its end compiles and panics?For a fixed-size array indexed by a constant, rustc can prove the access always fails, and the deny-by-default `unconditional_panic` lint turns it into a compile error: `this operation will panic at runtime`. A `Vec`'s length is only known at run time, so its bounds check happens when the code runs and panics then.
- When `unwrap` fails inside a helper function, which file and line does the panic message report?The line where `unwrap` was called. `Option::unwrap`, `Result::unwrap` and the `expect` methods are marked `#[track_caller]`, so the location is the caller's, not a line inside the standard library. For `Result`, the message also includes the `Err` value's `Debug` output, which is why those methods require `E: Debug`.
- Should a Rust library function panic when its caller passes an invalid argument?Usually it should return an error so the caller decides. Panicking fits when the argument breaks a documented contract and continuing would be insecure or meaningless, as with slice indexing, and the function then states it in a `# Panics` doc section. A library should not panic on data that comes from outside the program.
- A panic is Rust's exception, so catch it to handle bad user input.
- expect handles the error more gracefully than unwrap does.
- Indexing a Vec out of bounds returns a default value or garbage.
- Malformed input is unexpected, so the handler should panic on it.
- A panic always kills every thread in the process immediately.