panic! vs Recoverable Errors
Panics abort unwinding (or abort strategy) for bugs or unrecoverable states. Result handles expected failures callers can respond to.
Busca en todas las páginas de la documentación
Panics abort unwinding (or abort strategy) for bugs or unrecoverable states. Result handles expected failures callers can respond to.
fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
if b == 0 { Err("division by zero") } else { Ok(a / b) }
}
fn index_unchecked(v: &[i32], i: usize) -> i32 {
v[i] // panics if out of bounds - programmer error if misused
}When to reach for this: Result for I/O and validation; panic!/assert! for invariant violations and prototype unwrap.
fn parse_config(s: &str) -> Result<u16, String> {
s.trim().parse::<u16>()
.map_err(|e| format!("invalid port: {e}"))
}
fn main() {
match parse_config("8080") {
Ok(p) => println!("{p}"),
Err(e) => eprintln!("config error: {e}"),
}
}What this demonstrates:
Result| Use panic | Use Result |
|---|---|
| Logic bug, impossible branch | Network down, bad user input |
assert! in tests | Library public APIs |
unwrap in main prototype | Servers and libraries |
std::panic::catch_unwind rarely in app code - not for normal errors.
unwrap in library - Panics caller's thread. Fix: Return Result.Result or Option.panic=abort in release changes unwinding. Fix: Know profile settings.v[i] panics. Fix: get(i) for user indices.
| Alternative | Use When | Don't Use When |
|---|---|---|
Result | Recoverable | Truly impossible if preconditions met |
Option | Absence not error | Need failure reason |
assert! / debug_assert! | Invariants | User input validation |
NonZero types | Prove non-zero at type level | Optional values |
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+.
Revisado por Chris St. John·Última actualización: 19 jul 2026