Error Handling

Rust error handling is built around Result for recoverable failures, panic! for broken invariants, and error types that preserve enough information for callers and operators.

What it is

This MOC links the atomic notes for the Error Handling domain. Start with Recoverable vs Unrecoverable Errors, then read Result, The Question Mark Operator, and panic!.

The practical center is simple: model expected failure in types, propagate with ?, add context where it matters, and reserve panics for bugs.

Concepts

Patterns

Antipatterns

How it works

The notes are intentionally layered. The concept notes define the language and standard-library contracts. The pattern notes show idiomatic ways to structure real code. The antipattern notes mark the places where Rust code often compiles but loses reliability or caller agency.

Example

use std::fs;
use std::io;
 
fn load_name(path: &str) -> Result<String, io::Error> {
    let name = fs::read_to_string(path)?;
    Ok(name.trim().to_string())
}
 
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let name = load_name("name.txt")?;
    println!("hello, {name}");
    Ok(())
}

Best practice

Pitfalls

See also

Recoverable vs Unrecoverable Errors · Result · The Question Mark Operator · panic! · The Error Trait · Custom Error Types · Error Handling with thiserror · Application Errors with anyhow

Sources