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:
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
cargo new adder
cd adder
printf '10\n20\n\n12\n' > numbers.txt
Put this in src/main.rs:
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:
cargo add thiserror
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:
cargo add anyhow
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_totalskip 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 anOption, and.ok_or(...)turns that into aResult. - 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.
Cloud
More like this
Cloud
Build a Tiny JSON API With Axum: Rust on the Web in Fifteen Minutes
Your Rust programs have been talking to the terminal. Time they talked to the internet. Build a notes API with Axum, with routes, JSON in and out, shared state and proper 404s, in about 50 lines.
Cloud
Ollama Review: Running Local LLMs on Your Own Machine, No Cloud Required
What if your AI assistant lived in your basement instead of someone else's data centre? A review of Ollama: how to run local LLMs with it, what hardware you really need, the API that makes it useful, and where it falls short.
Cloud
Async Rust With Tokio: Build an Echo Server That Juggles a Thousand Clients
One waiter, forty tables, and nobody waits for their soup. That's async. Learn async Rust with Tokio by building a 30-line TCP echo server, then meet the one mistake that freezes the whole restaurant.