Sub topic 4
Propagating errors with ?
This chapter assumes you know how Result<T, E> and Option<T> work, how to use match, and why unwrap can panic. You should also be able to run a Cargo project. Here we use ? on Result. Later chapters cover Option and error conversion in more detail.
The problem with manual propagation
Many functions only need to pass a failure up to their caller. Written with match, each fallible call adds a branch:
use std::fs::File;
use std::io::{self, Read};
fn read_username(path: &str) -> Result<String, io::Error> {
let mut file = match File::open(path) {
Ok(f) => f,
Err(e) => return Err(e),
};
let mut name = String::new();
match file.read_to_string(&mut name) {
Ok(_) => Ok(name),
Err(e) => Err(e),
}
}The success path is buried in error plumbing. Every Err arm does the same thing: return the error to the caller.
The ? operator
Putting ? after an expression of type Result does that job in one character:
use std::fs::File;
use std::io::{self, Read};
fn read_username(path: &str) -> Result<String, io::Error> {
let mut file = File::open(path)?;
let mut name = String::new();
file.read_to_string(&mut name)?;
Ok(name)
}The behavior of expr? depends on the value:
- If it is
Ok(v), the whole expression evaluates tovand execution continues. - If it is
Err(e), the function returns immediately withErr(e). The error is passed throughFrom::from, which is a no-op when the types already match.
The function still returns a Result. ? does not handle the error. It moves the decision to the caller.
Chaining calls
Because ? yields the unwrapped value, you can chain method calls on it:
use std::fs;
use std::io;
fn read_trimmed(path: &str) -> Result<String, io::Error> {
let text = fs::read_to_string(path)?;
Ok(text.trim().to_string())
}
fn main() {
match read_trimmed("name.txt") {
Ok(name) => println!("hello, {name}"),
Err(e) => eprintln!("could not read file: {e}"),
}
}Here main is the caller that finally handles the error. Each function between the failure and main only needs ?.
The rule: the return type must fit
? expands to an early return, so the enclosing function must return a type that can hold the error. The most common mistake is using ? in a function that returns ():
use std::fs;
fn main() {
let text = fs::read_to_string("name.txt")?;
println!("{text}");
}This does not compile. The compiler reports that the ? operator can only be used in a function that returns Result or Option. The fix is to change the signature, or to handle the error locally with match.
Error types must match, or convert
In the examples above, every call produced an io::Error, and the function returned io::Error. If one call produced a different error type, the function would need a way to convert it. ? supports this through the From trait. The next chapters show how that conversion works and how to design a return type that accepts several error kinds.
Exercise
The function below fails to compile. Explain why, and give the corrected signature. fn double(s: &str) -> i32 { let n: i32 = s.parse()?; n * 2 }
Show answer
parse returns a Result, so ? may return early with an Err. The function returns i32, which cannot hold an error, so the compiler rejects it. Change the signature to fn double(s: &str) -> Result<i32, std::num::ParseIntError> and end the body with Ok(n * 2).
Exercise
In File::open(path)?, what happens to the value if the file does not exist, and what does the caller of read_username receive?
Show answer
File::open returns Err(io::Error). ? returns from read_username immediately, so the remaining lines never run. The caller receives Err(io::Error) and must decide how to handle it.