Error Handling Basics
8 examples - 5 basic, 3 intermediate - covering Option, Result, and when to panic.
Search across all documentation pages
8 examples - 5 basic, 3 intermediate - covering Option, Result, and when to panic.
Option for Missing Valuesfn find(ids: &[u32], target: u32) -> Option<usize> {
ids.iter().position(|&id| id == target)
}None means not found without error detailSome(i) carries indexResult for Failuresuse std::fs;
fn read(path: &str) -> Result<String, std::io::Error> {
fs::read_to_string(path)
}Err includes error reasonOk on successResultmatch on Resultfn main() {
match read("Cargo.toml") {
Ok(body) => println!("{body}"),
Err(e) => eprintln!("{e}"),
}
}unwrap and expect (prototypes)let n: u32 = "42".parse().expect("valid port");Err - binaries/prototypes onlyResult? Propagation Previewfn load() -> Result<String, std::io::Error> {
let s = std::fs::read_to_string("config.toml")?;
Ok(s)
}Related: The ? Operator
Option and Resultfn first_user(names: &[&str]) -> Result<&str, &'static str> {
names.first().ok_or("empty list")
}map and and_thenlet port: Option<u16> = Some("8080")
.and_then(|s| s.parse().ok());enum AppError { Io(std::io::Error), Parse(std::num::ParseIntError) }Related: Error Handling Best Practices
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+.
Reviewed by Chris St. John·Last updated Jul 16, 2026