Rust Error Handling: The Question Mark That Saves Your Program

Ever told a joke, been heckled, and just walked off stage mid-sentence? Most programs handle errors like that. Rust makes you plan for the heckler. A ten-minute lab with ?, Result, thiserror and anyhow.

Ada Brackett

4 min read

Have you ever been halfway through a joke when someone in the back yells "That's not a number!", and instead of answering you just... walk off stage? No goodbye, no punchline, lights still on?

That's how a lot of programs handle errors. Something unexpected happens and the whole show ends with a stack trace. Rust error handling works differently: Rust doesn't let you go on stage until you've planned for the heckler.

Last week's word counter had a homework hint: reading a file returns a Result. Today we work out what to do with one. Ten minutes, one file of numbers, zero walking off stage.

The heckler is a type

In Rust, a function that might fail says so in its signature:

Rust
fn read_to_string(path: &str) -> Result<String, std::io::Error>

Result has exactly two outcomes: Ok(value) when the show went well, or Err(error) when it didn't. You can't use the String until you've opened the envelope and checked which one you got. The compiler won't let you skip it. It's the stage manager holding the curtain.

Make a tiny adding machine

Bash
cargo new adder
cd adder
printf '10\n20\n\n12\n' > numbers.txt

Put this in src/main.rs:

Rust
use std::error::Error;
use std::fs;

fn read_total(path: &str) -> Result<i64, Box<dyn Error>> {
    let text = fs::read_to_string(path)?;
    let mut total = 0;
    for line in text.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        total += line.parse::<i64>()?;
    }
    Ok(total)
}

fn main() {
    match read_total("numbers.txt") {
        Ok(total) => println!("total: {total}"),
        Err(e) => eprintln!("couldn't add it up: {e}"),
    }
}

cargo run:

total: 42

The answer to everything, obviously. Now, about that little ?.

The question mark, explained

? means: "If this worked, give me the value and keep going. If it failed, stop this function right here and hand the error back to whoever called me."

So fs::read_to_string(path)? either gives you the text or bails out of read_total with the error. line.parse::<i64>()? either gives you a number or bails out with the parse error. The one character does the work of four lines of match.

Box<dyn Error> is the "any kind of error will do" return type. A missing file and a bad number are different types, and the box holds either one.

Now heckle it. Delete the file:

couldn't add it up: No such file or directory (os error 2)

Put banana on a line:

couldn't add it up: invalid digit found in string

No crash. The program caught the heckle and answered it. But "invalid digit found in string" is a bit vague. Which string? Which line? The banana deserves better.

Errors with personality: thiserror

For a library, or any code where callers need to know what went wrong, give your errors a proper type. The thiserror crate makes that painless:

Bash
cargo add thiserror
Rust
use std::fs;

#[derive(Debug, thiserror::Error)]
enum TotalError {
    #[error("couldn't read {path}: {source}")]
    Read { path: String, source: std::io::Error },
    #[error("line {line}: {value:?} is not a number")]
    NotANumber { line: usize, value: String },
}

fn read_total(path: &str) -> Result<i64, TotalError> {
    let text = fs::read_to_string(path)
        .map_err(|source| TotalError::Read { path: path.to_string(), source })?;
    let mut total = 0;
    for (i, line) in text.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let n: i64 = line.parse().map_err(|_| TotalError::NotANumber {
            line: i + 1,
            value: line.to_string(),
        })?;
        total += n;
    }
    Ok(total)
}

Keep the same main. Now the banana gets named and shamed:

couldn't add it up: line 3: "banana" is not a number

map_err turns the original error into yours, and ? still does the bailing out. A caller can match on TotalError::NotANumber and do something clever, like ask the user to take the fruit out of their spreadsheet.

Apps just want context: anyhow

In an application (the thing at the very top, with a main), you usually don't need fancy types. You just want the message to say what you were trying to do. That's anyhow:

Bash
cargo add anyhow
Rust
use anyhow::Context;

fn main() -> anyhow::Result<()> {
    let text = std::fs::read_to_string("numbers.txt")
        .context("reading the numbers file")?;
    println!("{} lines", text.lines().count());
    Ok(())
}

If the file is missing, main returns the error and Rust prints it with its whole story: what you were doing, then why it failed. The usual rule of thumb is thiserror for libraries, anyhow for apps, and plenty of projects use both.

A word about unwrap()

You'll see .unwrap() everywhere in examples. It means "I'm sure this worked, and if it didn't, crash." That's walking off stage. .expect("config file must exist") is the same thing with a farewell speech. They're fine in quick experiments and in tests, and best kept out of code that real people run.

Homework

  • Make read_total skip lines that start with #, so your numbers file can have comments.
  • Add a third error variant for totals that overflow, using checked_add. Hint: it returns an Option, and .ok_or(...) turns that into a Result.
  • Chapter 9 of the Rust Book, "Error Handling", is free at doc.rust-lang.org/book.

Rust can't stop the heckler showing up. It just makes sure you always have a comeback.