Rust has no exceptions. A function that can fail returns a Result, and the ? operator passes the error up to its caller. This part covers panic, Result, unwrap, ?, and writing your own error type.
Rust has no exceptions. A function that can fail says so in its return type, with Result, and the caller has to deal with it. When something goes wrong that should never happen, the program panics and stops.
This part covers both: panic! and Result, unwrap and expect, the ? operator, and how to build an error type of your own. It leans on enums and match from Part 11, because Result is just an enum. Every program here was run on Rust 1.95, and its output is pasted from the run.
Try this first
This program turns four pieces of text into numbers. Decide what it prints before you scroll down:
fn main() {
let inputs = ["42", "-7", "4 2", "100"];
for text in inputs {
let n: i32 = text.parse().unwrap();
println!("{text} -> {n}");
}
}
It prints:
42 -> 42
-7 -> -7
panicked at src/main.rs:4:35:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
The first two work. "4 2" has a space in the middle, so it isn’t a number, and the program stops. "100" never gets a turn.
parse didn’t stop the program. It returned a value that said “this failed”, and unwrap turned that into a panic. Most of this part is about doing something better with that value.
Two kinds of failure
Some failures are part of normal life. A user types “4 2” where you asked for a number. A file isn’t there. A network is down. Your program should expect these and handle them.
Other failures mean the program itself is wrong. An index is past the end of an array. A value that should never be zero is zero. There’s no sensible way to carry on, because the code has a bug.
Rust uses a different tool for each:
Result<T, E>for failures you expect. The function returns eitherOkwith a value of typeTorErrwith an error of typeE. The caller decides what to do.panic!for bugs. The program prints a message and stops.
You’ve already seen panics: overflow in Part 2 and an index out of range in Part 4. You can also panic on purpose:
fn grade(score: u8) -> char {
if score > 100 {
panic!("score must be 0 to 100, got {score}");
}
if score >= 50 { 'P' } else { 'F' }
}
fn main() {
println!("{}", grade(72));
println!("{}", grade(140));
}
It prints:
P
panicked at src/main.rs:3:9:
score must be 0 to 100, got 140
panic! takes a format string, like println!. Here a score over 100 means another part of the program has a bug, so stopping is right. But if 140 could come from a user typing it in, a panic would be wrong. A typo isn’t a bug in your program. That’s when you return a Result.
Result is an enum
Result lives in the standard library, and it’s an ordinary enum like the ones in Part 11:
enum Result<T, E> {
Ok(T),
Err(E),
}
T and E stand for any two types. Part 15 covers these type parameters properly; for now, read Result<i32, ParseIntError> as “either an i32, or a ParseIntError saying why there isn’t one”.
parse returns exactly that. So you can match on it, the same as on any enum:
fn main() {
let inputs = ["42", "4 2", "", "99999999999", "+7"];
for text in inputs {
match text.parse::<i32>() {
Ok(n) => println!("{text:?}: the number {n}"),
Err(e) => println!("{text:?}: error, {e}"),
}
}
}
It prints:
"42": the number 42
"4 2": error, invalid digit found in string
"": error, cannot parse integer from empty string
"99999999999": error, number too large to fit in target type
"+7": the number 7
parse::<i32>() uses the turbofish from Part 2 to say which type we want. The error is a std::num::ParseIntError. Printed with {e}, it gives a sentence a person can read. Printed with {e:?}, the Debug form, it gives ParseIntError { kind: InvalidDigit }, which is for programmers.
You can’t forget the error. A Result<i32, ParseIntError> isn’t an i32, so you can’t do sums with it until you’ve taken the number out, and that means saying what happens when there isn’t one.
unwrap and expect
match is the full answer, but it’s a lot of typing when you’re sure the value is there. Two methods take the shortcut:
unwrap()gives you theOkvalue, or panics with the error’s Debug form.expect("message")does the same, but puts your message first.
fn main() {
let port: u16 = "8080".parse().expect("8080 is a valid port");
println!("port {port}");
let typed = "80a";
let port: u16 = typed.parse().expect("the port must be a number");
println!("port {port}");
}
It prints:
port 8080
panicked at src/main.rs:6:35:
the port must be a number: ParseIntError { kind: InvalidDigit }
Read the panic as two halves joined by a colon: your message, then the error. That’s why expect beats unwrap. When it fires, you know which of your assumptions was wrong.
Both are fine when the value can’t be an error, like "8080".parse() on text written into the program, and in tests and quick experiments, where a panic is the report you want. When the text comes from outside your program, return the error instead. That’s the next section.
If a fallback really is the right answer, unwrap_or(0) gives you 0 instead of panicking.
Passing an error up with ?
Most functions that hit an error can’t fix it themselves. The best they can do is hand it to whoever called them. Here’s a function that adds two numbers written as text, handing the error up by hand:
use std::num::ParseIntError;
#[allow(clippy::question_mark)]
fn add_text(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = match a.trim().parse::<i32>() {
Ok(n) => n,
Err(e) => return Err(e),
};
let y = match b.trim().parse::<i32>() {
Ok(n) => n,
Err(e) => return Err(e),
};
Ok(x + y)
}
fn main() {
println!("{:?}", add_text("2", " 40"));
println!("{:?}", add_text("2", "forty"));
}
It prints:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
use std::num::ParseIntError; lets us write the short name instead of the full path. The #[allow(...)] line asks Clippy, Rust’s style checker, to stay quiet about this function. Clippy spots this exact pattern and suggests the shortcut we’re about to meet. Each match does the same job: take the number out, or return the error from add_text right away. That return is an early return. The lines below it never run.
That pattern is so common that Rust gives it one character. The ? operator does exactly this:
use std::num::ParseIntError;
fn add_text(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x: i32 = a.trim().parse()?;
let y: i32 = b.trim().parse()?;
Ok(x + y)
}
fn main() {
println!("{:?}", add_text("2", " 40"));
println!("{:?}", add_text("2", "forty"));
}
It prints:
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
Same output. ? goes after an expression that gives a Result. If it’s Ok(v), the whole expression becomes v. If it’s Err(e), the function returns Err at once.
There’s one more step in it, and it matters later. Written out, expr? is close to this:
match expr {
Ok(v) => v,
Err(e) => return Err(From::from(e)),
}
From::from(e) converts the error into the error type of the function you’re in. When the two types are the same, as in add_text, it hands e back unchanged. When they’re different, it’s what lets ? change one error into another. We’ll use that in a moment.
Two rules follow from the expansion. ? can only be used inside a function that returns a Result (or an Option, below), because it has to be able to return Err(...). And the error has to be convertible into the function’s error type.
? in main
Since ? returns from the function it’s in, using it in an ordinary main doesn’t compile:
fn main() {
let port: u16 = "80a".parse()?;
println!("port {port}");
}
It prints:
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
...
1 | fn main() {
| --------- this function should return `Result` or `Option` to accept `?`
2 | let port: u16 = "80a".parse()?;
| ^ cannot use the `?` operator in a function that returns `()`
...
help: consider adding return type
|
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
main returns (), the empty value, so ? has nowhere to send an Err. The help: line shows the fix, and it’s one you’ll write often:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let port: u16 = "8080".parse()?;
println!("port {port}");
let port: u16 = "80a".parse()?;
println!("port {port}");
Ok(())
}
It prints:
port 8080
Error: ParseIntError { kind: InvalidDigit }
Box<dyn Error> is a trait object, which Part 21 explains. For now, read it as “any error”. A ParseIntError fits, and so does nearly every error type in the standard library. Because main now returns a Result, it has to end with Ok(()): success, with nothing in it.
When main returns Err, Rust prints Error: and the error, and exits with code 1. A panic exits with code 101. (We checked both with echo $? after cargo run.) Notice the Debug form, ParseIntError { kind: InvalidDigit }, not the readable sentence. That’s fine for a small tool. A program that people use should print the message itself.
? works on Option too
An Option (Part 11) can use ? as well. On None, the function returns None at once:
fn first_digit_doubled(text: &str) -> Option<u32> {
let first = text.chars().next()?;
let digit = first.to_digit(10)?;
Some(digit * 2)
}
fn main() {
println!("{:?}", first_digit_doubled("7up"));
println!("{:?}", first_digit_doubled(""));
println!("{:?}", first_digit_doubled("x1"));
}
It prints:
Some(14)
None
None
chars().next() gives the first character, or None for empty text. to_digit(10) gives the digit’s value, or None if the character isn’t a digit. Each ? stops at the first None.
What ? won’t do is mix the two. In a function that returns Result, ? on an Option fails to compile with E0277, because None doesn’t say what went wrong. The compiler’s message suggests the fix: “use .ok_or(...)? to provide an error”. ok_or turns Some(v) into Ok(v), and None into Err with the error you give it:
fn last_number(text: &str) -> Result<i32, String> {
let word = text.split(' ').next_back();
let last = word.ok_or(String::from("no words"))?;
let n: i32 = last.parse().map_err(|e| format!("{last:?}: {e}"))?;
Ok(n)
}
fn main() {
println!("{:?}", last_number("total 12"));
println!("{:?}", last_number("total twelve"));
}
It prints:
Ok(12)
Err("\"twelve\": invalid digit found in string")
The second ? meets the opposite problem. parse fails with a ParseIntError, but last_number returns a String error. map_err changes the error inside a Result and leaves an Ok alone. |e| format!(...) is a closure, a small function written in place; Part 16 covers closures. Read it as “take the error e and build this text from it”.
Your own error type
A String error is easy to make and hard to use. The caller can print it, but it can’t tell one kind of failure from another without reading the text. Real code makes an enum, one variant per way things can fail.
Say we’re loading a config that should look like port=8080. Two things can go wrong: the port= part is missing, or the value isn’t a number.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
MissingPort,
BadPort(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::MissingPort => write!(f, "no port= in the config"),
ConfigError::BadPort(e) => write!(f, "the port is not a number ({e})"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadPort(e)
}
}
fn parse_port(text: &str) -> Result<u16, ParseIntError> {
let port: u16 = text.trim().parse()?;
Ok(port)
}
fn load_config(config: &str) -> Result<u16, ConfigError> {
let value = config
.strip_prefix("port=")
.ok_or(ConfigError::MissingPort)?;
let port = parse_port(value)?;
Ok(port)
}
fn main() {
for config in ["port=8080", "port=80a", "host=example.com"] {
match load_config(config) {
Ok(port) => println!("{config}: port {port}"),
Err(e) => println!("{config}: could not load config: {e}"),
}
}
}
It prints:
port=8080: port 8080
port=80a: could not load config: the port is not a number (invalid digit found in string)
host=example.com: could not load config: no port= in the config
There are three impl blocks here, and each one implements a trait: a set of methods a type promises to have. Part 14 covers traits. For now, here’s what each one buys us:
Displaysays how to print the error for a person, with{e}. Itsfmtmethod writes text withwrite!, which works likeprintln!but writes intof.std::error::Errormarks the type as an error. It needs no methods of its own, so the block is empty. It’s what lets?turn aConfigErrorinto aBox<dyn Error>, in amainlike the one in the last section.From<ParseIntError>says how to make aConfigErrorfrom aParseIntError. This is the one?uses.
BadPort holds the original ParseIntError, so nothing is lost. The message still says why the number was bad.
strip_prefix("port=") returns the text after port=, or None if the text doesn’t start with it. ok_or turns that None into our own error, so the ? after it fits.
Watching ? climb the call stack
Look at the line let port = parse_port(value)?; in load_config. parse_port returns a ParseIntError, but load_config returns a ConfigError. Without the From block, this line wouldn’t compile. With it, ? converts the error on its way out.
The animation follows load_config("port=80a"). Each function call gets a frame, its own space on the stack for its local variables. A new call goes on top, and a returning call comes off.
Each ? that meets an Err returns from its function at once. The error travels down the stack one frame at a time, and changes type where a From conversion is needed.
Here are those steps in words, in case the animation doesn’t play for you:
maincallsload_config("port=80a"), which callsparse_port("80a"). There are three frames on the stack, andparse_port, on top, is running."80a"isn’t a number, soparsegivesErr(ParseIntError). The?after it returns thatErrfromparse_portstraight away. The lineOk(port)never runs.parse_port‘s frame comes off the stack. TheErrarrives inload_config, as the value ofparse_port(value).- The
?on that line callsFrom::fromon the error. OurFromblock turns theParseIntErrorintoConfigError::BadPort, because that’s the error typeload_configreturns. - That
?returns the convertedErrfromload_configat once, so its last line never runs either. Its frame comes off the stack too. maingetsErr(ConfigError::BadPort(...)). Itsmatchtakes theErrarm and prints the message. Nothing panicked, and the loop goes on to the next config.
Nothing here is hidden. Every function that can fail says so in its return type, and every place an error can leave a function is marked with ?. You can find all of them by reading the code.
map_err when From can’t tell
From picks the conversion by type alone. That’s a problem when one function can fail in two places with the same error type. Here a size like 80x24 has two numbers, and each can be bad. A From<ParseIntError> block couldn’t know which one failed. map_err lets each call say:
use std::num::ParseIntError;
#[derive(Debug)]
enum SizeError {
NoX,
BadWidth(ParseIntError),
BadHeight(ParseIntError),
}
fn parse_size(text: &str) -> Result<(u32, u32), SizeError> {
let (w, h) = text.split_once('x').ok_or(SizeError::NoX)?;
let width = w.parse().map_err(SizeError::BadWidth)?;
let height = h.parse().map_err(SizeError::BadHeight)?;
Ok((width, height))
}
fn main() {
for text in ["80x24", "80-24", "eightyx24", "80x"] {
match parse_size(text) {
Ok((w, h)) => println!("{text:?}: {w} by {h}"),
Err(SizeError::NoX) => println!("{text:?}: no x between the numbers"),
Err(SizeError::BadWidth(e)) => println!("{text:?}: bad width, {e}"),
Err(SizeError::BadHeight(e)) => println!("{text:?}: bad height, {e}"),
}
}
}
It prints:
"80x24": 80 by 24
"80-24": no x between the numbers
"eightyx24": bad width, invalid digit found in string
"80x": bad height, cannot parse integer from empty string
split_once('x') splits the text at the first x into a pair, or gives None if there’s no x. Then map_err(SizeError::BadWidth) wraps a width error in the BadWidth variant. A variant that holds one value can be used like a function that takes that value, so we don’t need a closure here.
Look at main, too. Because the error is an enum, the caller can match on each variant and react to each one differently. A String error couldn’t give it that.
Use From when every error of one type means the same thing to your function. Use map_err when the same error type can mean different things, or when you want to add detail, the way last_number did above.
Real projects rarely write all these impl blocks by hand. The thiserror crate writes Display and From for you from a short description on each variant, and anyhow gives applications one error type that holds any error plus some context. This series uses only the standard library, so we write them out. That’s also the best way to see what those crates do for you.
Worked example: an error the compiler explains
Delete the From block from the config program and build it again. Here’s the shortest version that shows the error:
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
BadPort(ParseIntError),
}
fn parse_port(text: &str) -> Result<u16, ParseIntError> {
let port: u16 = text.trim().parse()?;
Ok(port)
}
fn load_config(line: &str) -> Result<u16, ConfigError> {
let port = parse_port(line)?;
Ok(port)
}
fn main() {
println!("{:?}", load_config("80"));
}
It prints:
error[E0277]: `?` couldn't convert the error to `ConfigError`
...
13 | fn load_config(line: &str) -> Result<u16, ConfigError> {
| ------------------------ expected `ConfigError` because of this
14 | let port = parse_port(line)?;
| ----------------^ the trait `From<ParseIntError>` is not implemented for `ConfigError`
| |
| this can't be annotated with `?` because it has type `Result<_, ParseIntError>`
...
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
Read it from the top:
- The first line says what failed:
?tried to convert an error into aConfigErrorand couldn’t. - Line 13 is why the target is
ConfigError: it’s the error type inload_config‘s return type. - Line 14 shows the two sides.
parse_port(line)gives aResultwhose error isParseIntError, andConfigErrorhas noFrom<ParseIntError>. - The last note is the expansion from earlier, in the compiler’s words:
?converts errors withFrom.
There are two fixes. Add the From block, as in the full program above. Or convert at this one call with parse_port(line).map_err(ConfigError::BadPort)?, the way parse_size did. If many functions need the same conversion, write the From block once. If it’s one place, map_err is shorter.
Worked example: errors that say where
A real input has many lines, and “invalid digit found in string” doesn’t say which one is wrong. This program adds up the quantities in an order, one item,quantity per line, and every error names its line:
use std::error::Error;
fn total(order: &str) -> Result<u32, Box<dyn Error>> {
let mut sum = 0;
for (i, line) in order.lines().enumerate() {
let n = i + 1;
let (_, qty) = line.split_once(',').ok_or(format!("line {n}: no comma"))?;
let qty: u32 = qty
.trim()
.parse()
.map_err(|e| format!("line {n}: {qty:?} is not a quantity ({e})"))?;
sum += qty;
}
Ok(sum)
}
fn main() -> Result<(), Box<dyn Error>> {
for order in ["tea,2\ncake,1", "tea,2\ncake", "tea,2\ncake,one"] {
match total(order) {
Ok(sum) => println!("{sum} items"),
Err(e) => println!("error: {e}"),
}
}
let sum = total("pen,3\nink,4")?;
println!("last order: {sum} items");
Ok(())
}
It prints:
3 items
error: line 2: no comma
error: line 2: "one" is not a quantity (invalid digit found in string)
last order: 7 items
Some things to notice:
enumerate()gives each line with its index, counting from 0, soi + 1is the line number a person expects.totalreturnsBox<dyn Error>, so it can fail with errors of different types. AStringmade byformat!converts intoBox<dyn Error>with?, the same as aParseIntErrorwould.map_errkeeps the original message inside the new one, and adds the line and the bad text. Context like this is what makes an error message useful.mainusesmatchfor the first three orders, because we want to see every error. For the last one it uses?, because a bad order there should end the program.
Box<dyn Error> is the quick choice for a program. A library, which other code calls, should return an error enum like ConfigError, so its callers can match on the variants.
Tips and traps
unwrapon input from outside. It works on every test you type and panics on the first odd file a user gives it. Anything from a user, a file or the network should be handled withmatchor passed up with?.- “the
?operator can only be used in a function that returnsResult“. You used?in a function that returns something else, oftenmain. Change its return type toResult<(), Box<dyn Error>>and end it withOk(()). - “
?couldn’t convert the error to …”. The error type inside theResultdoesn’t match your function’s error type. Addimpl From<TheirError> for YourError, or usemap_errat that call. ?on anOptionin a function that returnsResult. It doesn’t compile, becauseNonecarries no error. Add.ok_or(your_error)before the?.- Panicking for a user’s mistake.
panic!is for bugs in your program. If the bad value can come from outside, return aResultand let the caller decide. - Throwing the cause away.
map_err(|_| MyError::Bad)drops the original error and its message. Keep it in the variant, the wayBadPort(ParseIntError)does.
A function that can fail says so in its return type, and
?hands the failure to the caller.
Exercises
Exercise 1. Change first_digit_doubled from the Option section so it returns Result<u32, String>. Empty text should give the error "empty text", and a first character that isn’t a digit should give "not a digit". Use ok_or and ?.
Exercise 2. This doesn’t compile. Make it compile, so that "ten" prints ten: not a number (invalid digit found in string). Don’t change parse_age or main.
use std::num::ParseIntError;
#[derive(Debug)]
enum AgeError {
NotANumber(ParseIntError),
TooOld(u8),
}
fn parse_age(text: &str) -> Result<u8, AgeError> {
let age = text.parse::<u8>()?;
if age > 130 {
return Err(AgeError::TooOld(age));
}
Ok(age)
}
fn main() {
for text in ["42", "ten", "200"] {
match parse_age(text) {
Ok(age) => println!("{text}: age {age}"),
Err(AgeError::NotANumber(e)) => println!("{text}: not a number ({e})"),
Err(AgeError::TooOld(age)) => println!("{text}: {age} is too old"),
}
}
}
It prints:
error[E0277]: `?` couldn't convert the error to `AgeError`
Exercise 3. Write fn port_arg(args: &[&str]) -> Result<u16, Box<dyn Error>>. It takes the second item of args (args.get(1) gives an Option), returns the error "no port given" if there isn’t one, and parses it as a u16 otherwise. Use ? for both. Hint: "some text" converts into Box<dyn Error> with ?, the same way a ParseIntError does. Print the result for ["app", "8080"], ["app"] and ["app", "http"], using {e} for errors.
Answers
1. Each ? gets an ok_or in front of it, and the last line wraps the value in Ok instead of Some:
fn first_digit_doubled(text: &str) -> Result<u32, String> {
let first = text.chars().next().ok_or("empty text")?;
let digit = first.to_digit(10).ok_or("not a digit")?;
Ok(digit * 2)
}
fn main() {
println!("{:?}", first_digit_doubled("7up"));
println!("{:?}", first_digit_doubled(""));
println!("{:?}", first_digit_doubled("x1"));
}
It prints:
Ok(14)
Err("empty text")
Err("not a digit")
ok_or("empty text") makes an Err holding a &str, not a String. The ? still works, because String has a From<&str>, so ? converts it for you.
2. Tell ? how to turn a ParseIntError into an AgeError, with a From block:
use std::num::ParseIntError;
#[derive(Debug)]
enum AgeError {
NotANumber(ParseIntError),
TooOld(u8),
}
impl From<ParseIntError> for AgeError {
fn from(e: ParseIntError) -> Self {
AgeError::NotANumber(e)
}
}
fn parse_age(text: &str) -> Result<u8, AgeError> {
let age = text.parse::<u8>()?;
if age > 130 {
return Err(AgeError::TooOld(age));
}
Ok(age)
}
fn main() {
for text in ["42", "ten", "200"] {
match parse_age(text) {
Ok(age) => println!("{text}: age {age}"),
Err(AgeError::NotANumber(e)) => println!("{text}: not a number ({e})"),
Err(AgeError::TooOld(age)) => println!("{text}: {age} is too old"),
}
}
}
It prints:
42: age 42
ten: not a number (invalid digit found in string)
200: 200 is too old
200 fits in a u8, whose largest value is 255, so it parses, and our own check catches it. "300" would fail in parse instead, as a NotANumber.
3. ok_or turns the missing item into an error, and both ? convert into Box<dyn Error>:
use std::error::Error;
fn port_arg(args: &[&str]) -> Result<u16, Box<dyn Error>> {
let text = args.get(1).ok_or("no port given")?;
let port = text.parse()?;
Ok(port)
}
fn main() {
let runs: [&[&str]; 3] = [&["app", "8080"], &["app"], &["app", "http"]];
for args in runs {
match port_arg(args) {
Ok(port) => println!("{args:?}: port {port}"),
Err(e) => println!("{args:?}: {e}"),
}
}
}
It prints:
["app", "8080"]: port 8080
["app"]: no port given
["app", "http"]: invalid digit found in string
args.get(1) gives an Option<&&str>, a reference to an item of the slice. text.parse() still works on it, because the dot follows references for you (Part 7). The array needs its type written out, [&[&str]; 3]. Without it, Rust reads &["app", "8080"] as a reference to an array of exactly two items, and then &["app"], with one item, doesn’t fit.
What’s next
We’ve used Vec in passing so far. In Part 13, we’ll meet the standard collections, Vec, HashMap, HashSet, BTreeMap and VecDeque, and see when to pick each one.