Error handling
Rust splits failures into recoverable Result errors and unrecoverable panics. Libraries return Result. Applications decide where to log, retry, or crash.
Detailed Explanation
A recoverable failure is one the caller might handle: file not found, a malformed port, a unique-constraint violation. Those are Result. An unrecoverable failure is a bug: an index you computed is out of range, an invariant you documented is false. Those are panics — unwrap on a broken invariant, unreachable!, or an explicit panic!.
The language does not have exceptions that you catch up the stack. ? returns the Err to the caller. A panic unwinds (or aborts, if you configured that), runs destructors, and stops the thread. You can catch a panic with std::panic::catch_unwind, and you almost never should outside a thread boundary or an FFI edge. It is not a control-flow tool.
A library crate should return Result<T, E> with an E that implements std::error::Error, Display, and Debug. The Error trait gives source() for a chain of causes. thiserror derives that enum for you. An application crate can use anyhow::Result<T> and ? everywhere, then print the chain at main. Mixing them is normal: libraries emit structured errors, binaries wrap them in anyhow.
Where you handle an error is a design choice. Handle it when you can do something: retry a timed-out request, fall back to a default config, tell the user the file is missing. Otherwise propagate. Logging every ? site produces noise and misses the site that actually decides. Convert errors at crate boundaries with From or map_err so the public E stays yours.
Panics in libraries are allowed for impossible states (slice[i] when i was already checked) and forbidden for expected input problems. A parser that unwraps on bad UTF-8 is a library bug. A parser that returns Err is the API.
What it costs: Result is a tagged union; on success paths ? is a branch the predictor hits. Building error values can allocate if E holds a String. Do not avoid Result for that reason on I/O paths. Do avoid format-heavy errors on a nanosecond-sensitive parse of trusted data.
When you return Result: expected failure. When you panic: a bug. When you catch_unwind: isolating a plugin or a thread, not replacing Result.
Code Examples
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
BadPort(std::num::ParseIntError),
}
fn load_port(raw: Option<&str>) -> Result<u16, ConfigError> {
let raw = raw.ok_or(ConfigError::Missing("PORT"))?;
raw.parse().map_err(ConfigError::BadPort)
}
fn main() {
match load_port(Some("xyz")) {
Ok(port) => println!("port {port}"),
Err(e) => println!("error {e:?}"), // prints: error BadPort(...)
}
}Common Gotchas
Panic is not an error-handling strategy
`catch_unwind` does not restore invariants your `Drop` impls assumed. Use `Result` for expected failures.
Handle or propagate, do not do both at every layer
Log once at the boundary that owns the decision. A `map_err` that only logs doubles the noise.
`unwrap` in a library on user input is a bug
Turn it into `Result`. Keep `unwrap` for invariants you have already proved.