In the previous lesson, the total function used a match only to say "if it fails, return the error to the caller (the function that called it) right away". With five steps that can each fail, you would write five matches with exactly the same body. Passing an error on to the caller, instead of handling it inside the function itself, is called error propagation. Rust has a small operator for it: ?.
The trainee cashier at Rusdi's Pancake Stall already has the same habit. They work through every order step by step: check the egg stock, read the cash handed over, calculate the change. When a step goes wrong, they don't invent a fix of their own. They stop and hand the problem to Rusdi right away, with a note saying what happened. When a step is fine, they continue to the next step. In code, the trainee cashier is the function, and Rusdi is the calling function. Each step is one piece of work that can fail, with ? after it. A step that is fine is an Ok: ? gives its value, and the next line runs. A problem with its note is an Err with its reason: ? returns it to the caller right away, and the remaining steps are skipped.
The ? operator: continue, or return the error
The program below reads a portion entry. read_portions turns text into a number, total uses read_portions, and both use ?:
use std::num::ParseIntError;
fn read_portions(entry: &str) -> Result<u32, ParseIntError> {
let portions = entry.trim().parse::<u32>()?;
Ok(portions)
}
fn total(price: u32, entry: &str) -> Result<u32, ParseIntError> {
let portions = read_portions(entry)?;
println!("portions read: {}", portions);
Ok(price * portions)
}
fn main() {
println!("{:?}", total(32, " 2 "));
println!("{:?}", total(32, "two"));
}
portions read: 2
Ok(64)
Err(ParseIntError { kind: InvalidDigit })
?goes after aResult. If it holdsOk(value),?givesvalue(here it goes intoportions), and the function continues. If it holdsErr(e), the function ends right there and returnsErr(e)to its caller.- For
"two",read_portionsreturns anErrtototal, and the?intotalpasses it on tomain. Theportions readline never runs: once there's an error, the rest of the function is skipped. - The function itself must return a
Result, and its success value is wrapped inOk(...). If you forget theOkand write justportionson the last line, the compiler refuses withexpected `Result<u32, ParseIntError>`, found `u32`.
? is only a shorthand. Without ?, read_portions is written as below, and it behaves exactly the same:
fn read_portions(entry: &str) -> Result<u32, ParseIntError> {
let portions = match entry.trim().parse::<u32>() {
Ok(p) => p,
Err(e) => return Err(e),
};
Ok(portions)
}
The same goes for reading a file: let contents = std::fs::read_to_string(path)?; gives the file's contents, or returns the std::io::Error (the error type for input and output) to the caller.
? only works in a function that returns Result or Option
What if read_portions returns a plain u32, but still uses ? inside? Before you look at the result, guess: does it compile?
fn read_portions(entry: &str) -> u32 {
let portions = entry.trim().parse::<u32>()?;
portions
}
fn main() {
println!("{}", read_portions("2"));
}
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
--> src/main.rs:2:47
|
1 | fn read_portions(entry: &str) -> u32 {
| ------------------------------------ this function should return `Result` or `Option` to accept `?`
2 | let portions = entry.trim().parse::<u32>()?;
| ^ cannot use the `?` operator in a function that returns `u32`
It doesn't compile. If the parse fails, ? has to return the error, but this function can only return a u32. The fix: change the return type to Result<u32, ParseIntError>, and return Ok(portions). A plain main can't use ? either, because main returns (). The way to let main use ? is in the section "Box
? on Option
? also works after an Option, in a function that returns an Option. ? gives the value inside a Some, or passes a None on to the caller right away. This example uses the price function from the previous lesson. price gives the price of a menu item inside a Some, or None when the item isn't on the menu:
fn price_of_two(a: &str, b: &str) -> Option<u32> {
Some(price(a)? + price(b)?)
}
price_of_two("sweet pancake", "iced tea") gives Some(37), and price_of_two("sweet pancake", "coffee") gives None, because coffee isn't on the menu. But ? doesn't mix Option and Result. price(menu)? in a function that returns Result<u32, String> is refused with the `?` operator can only be used on `Result`s, not `Option`s, in a function that returns `Result` . The compiler suggests use `.ok_or(...)?` . So give the None a reason first, with ok_or:
fn total(menu: &str, portions: u32) -> Result<u32, String> {
let h = price(menu).ok_or(format!("{} is not on the menu", menu))?;
Ok(h * portions)
}
total("egg pancake", 2) gives Ok(76), and total("coffee", 2) gives Err("coffee is not on the menu").
Your own error: StallError
An error that is a String can only be read by people. When a caller wants to react differently to each kind of problem, the error should be an enum, so that match can pick its variant. The program below makes the enum StallError and uses it in three functions: check_stock, pay and order:
use std::fmt;
#[derive(Debug)]
enum StallError {
OutOfStock,
ShortOfCash(u32),
}
impl fmt::Display for StallError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
StallError::OutOfStock => write!(f, "Out of eggs"),
StallError::ShortOfCash(short) => write!(f, "Short by {}", short),
}
}
}
impl std::error::Error for StallError {}
fn check_stock(egg_stock: u8, needed: u8) -> Result<(), StallError> {
if egg_stock < needed {
return Err(StallError::OutOfStock);
}
Ok(())
}
fn pay(total: u32, cash: u32) -> Result<u32, StallError> {
if cash < total {
return Err(StallError::ShortOfCash(total - cash));
}
Ok(cash - total)
}
fn order(egg_stock: u8, cash: u32) -> Result<u32, StallError> {
check_stock(egg_stock, 3)?;
let change = pay(102, cash)?;
Ok(change)
}
fn main() {
println!("{:?}", order(250, 110));
println!("{:?}", order(250, 100));
println!("{:?}", order(2, 110));
match order(250, 100) {
Ok(k) => println!("Change {}", k),
Err(e) => println!("Failed: {}", e),
}
}
Ok(8)
Err(ShortOfCash(2))
Err(OutOfStock)
Failed: Short by 2
- Each variant is one kind of problem.
ShortOfCash(u32)carries how much is missing, just likePayment::Cashin the enum lesson. Inorder(250, 100), the total is 102 and the cash is 100, so it is 2 short. #[derive(Debug)]gives the{:?}form (ShortOfCash(2)).impl fmt::Displaygives the sentence for the customer (Short by 2), written withwrite!as in the traits lesson.impl std::error::Error for StallError {}makesStallErroran official error: a type that has theErrortrait from the standard library. The curly braces are empty, because every method of theErrortrait is already a default method. TheErrortrait has only two requirements:StallErrormust haveDebugandDisplay. Thanks to this trait, aStallErrorfits into aBox<dyn Error>, which is covered below.Result<(), StallError>means "succeeded with no value, or failed".()is called unit: the empty value. That is whycheck_stockends withOk(()).orderuses?twice. Inorder(2, 110), a stock of 2 is less than the 3 eggs needed, so the first?returnsErr(OutOfStock)right away, andpayis never called.
From: so that ? can convert the error
Now order reads the cash from text. Inside order there is a new line: let cash = cash_text.trim().parse::<u32>()?;. When it fails, parse gives a ParseIntError, but order returns Result<u32, StallError>. So the compiler refuses with E0277 `?` couldn't convert the error to `StallError` and the trait `From<ParseIntError>` is not implemented for `StallError` . The note under it explains the main point: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait. This means that before ? passes an error on, it quietly converts that error through the From trait. So add a variant NotANumber for the error from parse, then write the conversion in impl From<ParseIntError> for StallError:
use std::num::ParseIntError;
#[derive(Debug)]
enum StallError {
OutOfStock,
ShortOfCash(u32),
NotANumber(ParseIntError),
}
// inside the match of impl fmt::Display, add one arm:
// StallError::NotANumber(e) => write!(f, "Cash is not a number: {}", e),
impl From<ParseIntError> for StallError {
fn from(e: ParseIntError) -> Self {
StallError::NotANumber(e)
}
}
fn order(egg_stock: u8, cash_text: &str) -> Result<u32, StallError> {
check_stock(egg_stock, 3)?;
let cash = cash_text.trim().parse::<u32>()?;
let change = pay(102, cash)?;
Ok(change)
}
The method from takes a ParseIntError and returns Self, the type written after for in this impl: StallError. With this impl, order(250, "110") gives Ok(8). order(250, "one hundred") gives Err(NotANumber(ParseIntError { kind: InvalidDigit })), which {} prints as Cash is not a number: invalid digit found in string. Another way without From: write .map_err(StallError::NotANumber)? on the parse line only. map_err changes the error inside the Err: here, the ParseIntError is wrapped in StallError::NotANumber.
Box in main
main may return a Result. The most flexible error type is Box<dyn Error>, which means "any error that has the Error trait". You know dyn from the traits lesson, and Box is covered in the next lesson. The main below reads a portion, then calls order twice:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let portions: u32 = "2".parse()?;
println!("Portions {}", portions);
let change = order(250, "110")?;
println!("Change {}", change);
let change = order(250, "100")?;
println!("Change {}", change);
Ok(())
}
Portions 2
Change 8
Error: ShortOfCash(2)
- In this
main,?converts bothParseIntErrorandStallErrorinto aBox<dyn Error>on its own, because both have theErrortrait. order(250, "100")fails because the cash is short. As soon asmainreturns anErr, Rust printsError:followed by itsDebugform (ShortOfCash(2), notShort by 2), and the program exits with code 1, the sign that it failed.Box<dyn Error>is handy formainand small programs. But a caller of a function that returnsBox<dyn Error>can't easily check which kind of error it got withmatch, because the real type is hidden. A function that other code uses should return an enum likeStallError.
📌 In the real world: thiserror and anyhow
Writing Display and From by hand is repetitive work. That is why nearly every Rust project uses two crates. A crate here is a library (ready-made code written by others) from the crates.io website. Crates are covered in the modules and Cargo lesson. thiserror (version 2.0.21 today) is for defining errors, and anyhow (version 1.0.104) is for accepting any error in an application. cargo add thiserror anyhow adds both crates to your project. After that, the code looks like this:
use anyhow::Context;
use thiserror::Error;
#[derive(Debug, Error)]
enum StallError {
#[error("Out of eggs")]
OutOfStock,
#[error("Short by {0}")]
ShortOfCash(u32),
#[error("Cash is not a number: {0}")]
NotANumber(#[from] std::num::ParseIntError),
}
// check_stock, pay and order exactly as above.
fn main() -> anyhow::Result<()> {
let change = order(250, "110").context("Budi's order failed")?;
println!("Change {}", change);
let change = order(250, "100").context("Sari's order failed")?;
println!("Change {}", change);
Ok(())
}
Change 8
Error: Sari's order failed
Caused by:
Short by 2
#[error("...")] writes the Display code for the variant under it ({0} becomes the first value in that variant), and #[from] writes the From code. anyhow::Result<()> is a Result with anyhow's error type, which can hold any error. .context(...) attaches a note on top of the original error. anyhow prints both: your note after Error:, then the original error under Caused by:. The usual guideline: thiserror for libraries (their callers need to match the variants), anyhow for applications (just report the error clearly).
⚠️ When does the compiler refuse the ? operator?
?in a function that doesn't returnResultorOption. E0277, plainfn main()included. Change the return type.- Forgetting
Ok(...)at the end.expected `Result<u32, ParseIntError>`, found `u32`. Wrap the success value inOk. ?on anOptionin a function that returnsResult. E0277. Use.ok_or(...)?.- A different error type with no
From.`?` couldn't convert the error to `StallError`. Writeimpl From<ParseIntError> for StallError, or use.map_err(...). - Expecting
mainto printDisplay. An error frommainis printed withDebug. If you need a tidy sentence, handle the error withmatchandprintln!("{}", e).
TL;DR: The ? operator passes an error on to the caller (the function that called this one), with no match. After a Result, ? gives the Ok value, or returns the Err to the caller right away. After an Option, ? gives the Some value, or passes the None on right away. ? only works in a function that returns Result or Option (otherwise E0277), and the success value is wrapped in Ok(...). Your own error is an enum like StallError { OutOfStock, ShortOfCash(u32) }, with #[derive(Debug)], impl fmt::Display and impl std::error::Error. Before ? passes an error on, it converts the error through the From trait. So with impl From<ParseIntError> for StallError, parse::<u32>()? works in a function whose error type is StallError. fn main() -> Result<(), Box<dyn Error>> accepts any error that has the Error trait, prints it with Debug and exits with code 1 (the sign that it failed). In real projects, two crates (libraries) help: thiserror (2.0.21) to define errors, and anyhow (1.0.104) for applications.
⚡ Continue, or hand it up
Write:
fn read_portions(entry: &str) -> Result<u32, ParseIntError> {
let portions = entry.trim().parse::<u32>()?;
Ok(portions)
}
Meaning: parse::<u32>() turns the text entry into a number, and it can fail with a ParseIntError. If the result is Ok, ? gives the value and the function continues. If it's Err, the function stops right there, and the error goes up to the caller (the function that called read_portions). No panic.
⚡ Only in a function that returns Result
Guess first: read_portions now returns a plain u32, not a Result, but still uses ? inside. Does it compile?
No. If the parse fails, ? has to return the error, but the function can only return a u32: E0277.
Meaning: ? only works in a function that returns Result or Option, and the success value is wrapped in Ok(...).
⚡ Your own error
Write:
#[derive(Debug)]
enum StallError {
OutOfStock,
ShortOfCash(u32),
}
Meaning: StallError is an enum for the stall's errors: OutOfStock (out of eggs) and ShortOfCash(u32) (not enough cash, and the u32 holds how much is missing). Each variant is one kind of problem, so a caller can react to each one differently through match. If you add impl From<ParseIntError> for StallError (how to turn a ParseIntError into a StallError), ? can turn the error from parse into a StallError on its own.