Answer#
A Result says "this can fail, and the caller decides what to do". A panic says "the program is wrong, stop here". Input from files, networks and people will be wrong sometimes; that is not a bug, so it must be a Result.
| Situation | Use |
|---|---|
| A file is missing, a request is malformed, a port string is not a number | Result |
| An index is out of range because of a logic error | panic (the standard indexing does this) |
A value that you have just checked cannot be None | expect("why this cannot happen") |
| A test asserts a result | assert! / unwrap() is fine |
use std::panic;
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.trim().parse() // anything from outside returns a Result, no unwrap
}
fn risky(items: &[i32], i: usize) -> i32 {
items[i] // panics when i is out of range
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("eighty"));
// A panic can be caught at a boundary (one request, one task). Works only with panic = "unwind".
panic::set_hook(Box::new(|_| {})); // keep this demo's output short
let r = panic::catch_unwind(|| risky(&[1, 2, 3], 7));
println!("caught a panic: {}", r.is_err());
let r = panic::catch_unwind(|| risky(&[1, 2, 3], 1));
println!("no panic: {:?}", r.ok());
}Ok(8080)
Err(ParseIntError { kind: InvalidDigit })
caught a panic: true
no panic: Some(2)A server normally catches panics per request (web frameworks do this for you) so that one bug ends one request and not the whole process. If you set panic = "abort" in the release profile, a panic ends the process and nothing can catch it.
Common mistakes#
- Using
unwrap()on aResultfrom a file or the network in production code. - Using
catch_unwindas a general error mechanism. It is for boundaries, not control flow. - Panicking in a library for bad arguments that the caller could cause; return an error, or document the panic in a
# Panicssection.
Related questions#
What does expect add over unwrap?#
A message that says why the value should be there. Use it to document an assumption, and the panic text then points at the broken assumption.
Sources#
- The Rust Book, "To panic! or Not to panic!": https://doc.rust-lang.org/book/ch09-03-to-panic-or-not-to-panic.html
- Standard library,
std::panic::catch_unwind: https://doc.rust-lang.org/std/panic/fn.catch_unwind.html