Level 1 · Foundations· Lesson 9 of 10 · 20 min
Error handling
Panics for bugs, Result for failures you expect, and the question-mark operator that makes propagation painless.
Two kinds of failure
Rust has no exceptions. It separates failures into two kinds and gives each its own mechanism.
- Bugs — an index out of bounds, a broken invariant, “this cannot happen”. These panic: the thread unwinds and, in a typical program, the process exits with a message.
- Expected failures — a file is missing, input is malformed, a connection drops. These are ordinary values of type
Result, and the type system makes callers deal with them.
Panics
fn main() {
let v = vec![1, 2, 3];
let index = v.len() + 2;
println!("about to fail");
println!("{}", v[index]); // panics: index out of bounds
}
You can panic deliberately with panic!("message"), and several macros panic for you: assert!, assert_eq!, unreachable!, todo!. A panic is not undefined behaviour — it is a controlled stop.
Result<T, E>
enum Result<T, E> {
Ok(T),
Err(E),
}
Any operation that can fail returns one:
fn main() {
let good: Result<i32, _> = "42".parse::<i32>();
let bad = "forty-two".parse::<i32>();
println!("{good:?}\n{bad:?}");
match "17".parse::<u8>() {
Ok(n) => println!("parsed {n}"),
Err(e) => println!("failed: {e}"),
}
}
The compiler warns if you ignore a Result, so failures cannot slip by unnoticed.
Propagating with ?
Most functions cannot do anything useful with an error except pass it up. The ? operator does exactly that:
use std::num::ParseIntError;
fn parse_pair(s: &str) -> Result<(i32, i32), ParseIntError> {
let (a, b) = s.split_once(',').unwrap_or((s, "0"));
let a = a.trim().parse::<i32>()?; // on Err, return it from parse_pair
let b = b.trim().parse::<i32>()?;
Ok((a, b))
}
fn main() {
println!("{:?}", parse_pair("3, 4"));
println!("{:?}", parse_pair("3, four"));
}
expr? means: if Ok(v), evaluate to v; if Err(e), return Err(e.into()) right now. It is a visible, one-character marker at every point where the function may exit early.
? also works on Option in functions that return Option.
Defining your own error type
When a function can fail in several ways, describe them with an enum:
use std::fmt;
#[derive(Debug)]
enum ConfigError {
Missing(String),
Invalid { key: String, value: String },
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(k) => write!(f, "missing key `{k}`"),
ConfigError::Invalid { key, value } => write!(f, "`{value}` is not valid for `{key}`"),
}
}
}
impl std::error::Error for ConfigError {}
fn port(line: &str) -> Result<u16, ConfigError> {
let value = line
.strip_prefix("port=")
.ok_or_else(|| ConfigError::Missing("port".into()))?;
value.parse().map_err(|_| ConfigError::Invalid {
key: "port".into(),
value: value.into(),
})
}
fn main() {
for line in ["port=8080", "host=x", "port=eighty"] {
match port(line) {
Ok(p) => println!("port {p}"),
Err(e) => println!("error: {e}"),
}
}
}
ok_or_else turns an Option into a Result; map_err converts one error type to another. Level 2 shows how the From trait and the thiserror and anyhow crates remove most of this boilerplate.
main can return a Result
use std::error::Error;
use std::fs;
fn main() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("definitely-missing.txt")?;
println!("{} bytes", text.len());
Ok(())
}
Box<dyn Error> means “any error type”. It is a fine choice for small programs. If main returns Err, the program prints the error and exits with a non-zero status.
unwrap and expect
Both extract the success value or panic. Use them when failure would be a bug, and prefer expect with a message explaining why it cannot fail:
fn main() {
let ip: std::net::IpAddr = "127.0.0.1"
.parse()
.expect("hard-coded address is valid");
println!("{ip}");
}
A rule of thumb: libraries return Result and let the caller decide; applications decide at the top level; unwrap is for prototypes, tests, and provable impossibilities.
Exercises
- Write
fn safe_div(a: f64, b: f64) -> Result<f64, String>that fails on division by zero. - Write
fn sum_numbers(s: &str) -> Result<i32, std::num::ParseIntError>that sums whitespace-separated integers, using?inside aforloop. - Extend
ConfigErrorwith a variantOutOfRange(u32)and makeportreturn it for values above 65535.
Solution to 2
fn sum_numbers(s: &str) -> Result<i32, std::num::ParseIntError> {
let mut total = 0;
for word in s.split_whitespace() {
total += word.parse::<i32>()?;
}
Ok(total)
}
fn main() {
println!("{:?}", sum_numbers("1 2 3"));
println!("{:?}", sum_numbers("1 two 3"));
}
Check your understanding
Pick an answer to see the explanation.
1.What does the
?operator do when applied to anErr(e)?2.When is
panic!the right tool?3.What must be true to use
?on aResultinside a function?