Error Handling

View saved

Propagate with ?

In a function that returns Result, ? returns early on Err.

use std::fs;
use std::io;

fn read_username() -> Result<String, io::Error> {
    let contents = fs::read_to_string("username.txt")?;
    Ok(contents.trim().to_string())
}

Convert error types later

Libraries often use Box<dyn Error> or crates like anyhow for apps. Start with concrete errors.

Handle in main

main can return a Result in modern Rust.

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let name = read_username()?;
    println!("{name}");
    Ok(())
}

Error habits

  • Reserve panic! for bugs, not expected failures
  • Add context when wrapping errors in larger apps
  • Log or display Err values at the top level
  • Combine with Option when absence is not an error

Comments

One comment per signed-in account. Comments are saved with this page’s URL.