Sub topic 4
Propagating errors with ?
This chapter shows how the ? operator replaces repetitive match blocks when a function should pass a failure up to its caller. It assumes you can write Rust functions and match expressions, know what Result<T, E> is (Ok or Err), and can build and run a Cargo project. Later chapters cover what ? expands to and how it converts error types. Here the focus is the everyday behavior: what ? does, where you write it, and how to read the results.
The problem: nested match
Suppose a function reads a username from a file. Two steps can fail: opening the file and reading its contents. Written with match only, the code looks like this:
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),
}
}
fn main() {
match read_username("username.txt") {
Ok(name) => println!("hello, {name}"),
Err(e) => eprintln!("could not read username: {e}"),
}
}Both match blocks do the same thing: on success, keep going with the value, and on failure, hand the error to the caller. This function does not know how to recover, so passing the error up is the right choice. The pattern is common enough that Rust gives it one character.
The ? operator
Put ? after an expression of type Result. If the value is Ok(v), the expression evaluates to v and execution continues. If the value is Err(e), the enclosing function returns immediately with that error.
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)
}
fn main() {
match read_username("username.txt") {
Ok(name) => println!("hello, {name}"),
Err(e) => eprintln!("could not read username: {e}"),
}
}The body now reads as the success path. Errors are still values, and they are still part of the function's signature. Nothing is hidden: the -> Result<String, io::Error> return type tells every caller that this function can fail.
Where you can write ?
? is a postfix operator, so it fits into expressions and method chains. These forms are all valid:
use std::num::ParseIntError;
fn sum_pair(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = a.trim().parse::<i32>()?;
let y = b.trim().parse::<i32>()?;
Ok(x + y)
}
fn double(s: &str) -> Result<i32, ParseIntError> {
Ok(s.trim().parse::<i32>()? * 2)
}
fn main() {
println!("{:?}", sum_pair("2", " 40 "));
println!("{:?}", sum_pair("2", "x"));
println!("{:?}", double("21"));
}Running this prints:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
Ok(42)Note the second call. The first ? succeeded, the second hit an Err, and sum_pair returned without computing x + y.
You can also chain calls in a single statement. ? applies to the result of the call just before it:
use std::fs::File;
use std::io::{self, Read};
fn read_username(path: &str) -> Result<String, io::Error> {
let mut name = String::new();
File::open(path)?.read_to_string(&mut name)?;
Ok(name)
}
fn main() {
match read_username("username.txt") {
Ok(name) => println!("hello, {name}"),
Err(e) => eprintln!("could not read username: {e}"),
}
}For this exact task the standard library has a helper, std::fs::read_to_string(path), which does both steps. The longer versions are useful because they show ? working on more than one call.
What the function must return
? can only return early if the function's return type has room for the error. The compiler checks this. For a Result expression, the function must also return a Result, and the error type of the expression must be convertible to the function's error type.
The simplest case is when the two types are identical, as in the examples above (io::Error to io::Error, ParseIntError to ParseIntError). Conversion between different types is possible too, using the From trait. A later chapter covers it. For now, keep the error types the same.
A very common mistake is using ? in a function that returns (), most often main. Consider a main declared as fn main() that calls File::open("x")?. The compiler rejects it with error E0277: the ? operator can only be used in a function that returns Result or Option (or another type that implements FromResidual). The function has no way to represent the failure, so there is nowhere to send it. There are two fixes:
- Change the function's return type to a
Result, and wrap the success value inOk(...). - Handle the error in place with
match,if let,unwrap_or, or a similar tool, so the function does not need to propagate it.
The main function can return a Result too. A later chapter in this tutorial covers that.
Adding context before the ?
Sometimes the raw error loses information. A ParseIntError says "invalid digit found in string" but not which input caused it. You can transform the error with map_err before applying ?:
fn parse_port(s: &str) -> Result<u16, String> {
let port = s
.trim()
.parse::<u16>()
.map_err(|e| format!("bad port {s:?}: {e}"))?;
Ok(port)
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
println!("{:?}", parse_port("70000"));
}Output:
Ok(8080)
Err("bad port \"abc\": invalid digit found in string")
Err("bad port \"70000\": number too large to fit in target type")Here map_err turns a ParseIntError into a String, and the function's error type is String, so the types line up at the ?. Using String as an error type is fine for small programs. Later chapters introduce better options.
Behavior to keep in mind
- Early return skips the rest of the function. Statements after a failing
?never run. Values already created in the function are dropped as usual, so aFileopened before the failure is closed automatically. ?does not log or print anything. The error travels silently up the call stack until some caller handles it. If nobody does, the error must end somewhere, such as amatchinmain.?works on one expression at a time. It does not combine several errors. The first failure wins and the rest of the work is not attempted.- The success value is moved out.
let file = File::open(path)?;gives you an ownedFile, not aResultwrapping it. - Closures count as functions. A
?inside a closure returns from the closure, not from the surrounding function. The closure's own return type must support it.
Where propagation fits
Propagate with ? when the current function cannot sensibly recover and the caller can decide what to do. Handle the error in place when you have a sensible fallback, such as a default value or a retry. Panic only for bugs or states that should be impossible. Libraries should almost always propagate. Applications usually propagate through many layers and handle the error once, near the top, where they can show a message or choose an exit code.
Exercise
The function below does not compile. Explain the two problems and write a corrected version that returns the sum of the two parsed numbers. fn add(a: &str, b: &str) -> i32 { let x = a.parse::<i32>()?; let y = b.parse::<i32>()?; x + y }
Show answer
The return type is i32, so ? has no way to return an Err. The compiler reports that ? can only be used in a function that returns Result or Option. The final expression x + y also has the wrong type once the return type changes, because it must be wrapped in Ok. A corrected version is:
fn add(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
let x = a.parse::<i32>()?;
let y = b.parse::<i32>()?;
Ok(x + y)
}
Both parse::<i32>() calls produce ParseIntError, which matches the function's error type, so no conversion is needed.
Exercise
In this function, what does the caller receive when path names a file that exists but contains bytes that are not valid UTF-8, and which line produces it?
fn readtext(path: &str) -> Result<String, std::io::Error> {
let mut file = std::fs::File::open(path)?;
let mut text = String::new();
file.readto_string(&mut text)?;
Ok(text)
}
Show answer
The caller receives an Err holding an io::Error with kind InvalidData, produced by the file.read_to_string(&mut text)? line. The File::open call succeeds because the file exists, so the first ? unwraps the File. Reading then fails on the invalid UTF-8, and the second ? returns the error immediately, skipping Ok(text). (The code also needs use std::io::Read; in scope for read_to_string to compile.)