Rust Error Handling
Things go wrong: a user types letters where a number belongs, a file is missing, a network times out. Rust splits errors into two groups and handles them differently:
| Kind | Example | Rust tool |
|---|---|---|
| Unrecoverable — a bug, the program cannot sensibly continue | indexing past the end of a vector | panic! |
| Recoverable — expected, the caller can react | invalid user input, missing file | Result<T, E> |
Most of your error handling will use Result. Panics are for situations that should never happen if the code is correct.
Panics
panic! stops the current thread, prints a message and unwinds the stack. Some standard operations panic too, such as unwrap() on None or dividing an integer by zero.
fn main() {
let v = vec![1, 2, 3];
let i = 7;
println!("{}", v[i]);
}thread 'main' panicked at src/main.rs:4:20:
index out of bounds: the len is 3 but the index is 7Use panic! (or unwrap/expect) only when continuing would be wrong — for example, when your own program's invariants are broken. For anything a user or the outside world can cause, return a Result instead.
Returning errors with Result
A function that can fail returns Result<T, E>. The caller decides what to do with the error.
fn withdraw(balance: u32, amount: u32) -> Result<u32, String> {
if amount == 0 {
return Err(String::from("amount must be greater than zero"));
}
if amount > balance {
return Err(format!("insufficient funds: balance {}, requested {}", balance, amount));
}
Ok(balance - amount)
}
fn main() {
let balance = 100;
for amount in [30, 0, 250] {
match withdraw(balance, amount) {
Ok(left) => println!("Withdrew {}, {} left", amount, left),
Err(e) => println!("Failed: {}", e),
}
}
}Withdrew 30, 70 left
Failed: amount must be greater than zero
Failed: insufficient funds: balance 100, requested 250
The ? operator
Calling several fallible functions in a row with match each time gets long. The ? operator is a shortcut: placed after a Result, it unwraps Ok, or returns the Err from the current function immediately.
use std::num::ParseIntError;
fn add_strings(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = a.trim().parse::<i32>()?; // on error, return it right away
let y = b.trim().parse::<i32>()?;
Ok(x + y)
}
fn main() {
println!("{:?}", add_strings("10", " 32 "));
println!("{:?}", add_strings("10", "ten"));
match add_strings("7", "x") {
Ok(sum) => println!("Sum: {}", sum),
Err(e) => println!("Error: {}", e),
}
}Ok(42)
Err(ParseIntError { kind: InvalidDigit })
Error: invalid digit found in string
? can only be used inside a function that itself returns a Result (or Option), because it needs somewhere to send the error. It also works on Option: None? returns None early.
Custom error types
A String error is easy, but an enum of error kinds lets callers react to each case differently. Implementing the Display trait gives each error a readable message, and implementing From lets ? convert other errors into yours automatically.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum OrderError {
NotANumber(ParseIntError),
TooMany(u32),
OutOfStock,
}
impl fmt::Display for OrderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
OrderError::NotANumber(e) => write!(f, "quantity is not a number ({})", e),
OrderError::TooMany(n) => write!(f, "cannot order {} items, max is 10", n),
OrderError::OutOfStock => write!(f, "item is out of stock"),
}
}
}
impl From<ParseIntError> for OrderError {
fn from(e: ParseIntError) -> Self {
OrderError::NotANumber(e)
}
}
fn place_order(qty_text: &str, in_stock: u32) -> Result<u32, OrderError> {
let qty: u32 = qty_text.parse()?; // ParseIntError -> OrderError via From
if qty > 10 {
return Err(OrderError::TooMany(qty));
}
if qty > in_stock {
return Err(OrderError::OutOfStock);
}
Ok(in_stock - qty)
}
fn main() {
let tests = [("3", 5), ("abc", 5), ("12", 50), ("4", 2)];
for (text, stock) in tests {
match place_order(text, stock) {
Ok(left) => println!("Order '{}' ok, {} left in stock", text, left),
Err(e) => println!("Order '{}' failed: {}", text, e),
}
}
}Order '3' ok, 2 left in stock
Order 'abc' failed: quantity is not a number (invalid digit found in string)
Order '12' failed: cannot order 12 items, max is 10
Order '4' failed: item is out of stock
main can return a Result
main may return Result<(), E>, so you can use ? directly inside it. If main returns an Err, the program prints the error and exits with a failure code. Using Box<dyn std::error::Error> as the error type accepts almost any error.
use std::error::Error;
fn parse_point(text: &str) -> Result<(i32, i32), Box<dyn Error>> {
let parts: Vec<&str> = text.split(',').collect();
if parts.len() != 2 {
return Err("expected two numbers separated by a comma".into());
}
let x = parts[0].trim().parse()?;
let y = parts[1].trim().parse()?;
Ok((x, y))
}
fn main() -> Result<(), Box<dyn Error>> {
let p = parse_point("4, -9")?;
println!("Point: {:?}", p);
if let Err(e) = parse_point("1,2,3") {
println!("Bad input: {}", e);
}
Ok(())
}Point: (4, -9)
Bad input: expected two numbers separated by a comma
Guidelines
- Return
Resultfrom any function that can fail because of input or the environment. - Use
?to pass errors upward instead of writing nestedmatchblocks. - Use
expect("why this can't fail")rather thanunwrap()when you are certain — the message helps the next reader. - Reserve
panic!for bugs, not for bad user input.
Note: In larger projects, popular crates such as
thiserrorandanyhowreduce the boilerplate of custom error types. The ideas are exactly the ones shown here.
Test yourself
What does the ? operator do when applied to an Err value?
- Panics
- Ignores the error and continues
- Returns the error from the current function
- Converts it to None
Which situation should usually be handled with Result rather than panic!?
- A user typed an invalid number
- An internal invariant your code guarantees is broken
- Unreachable code was reached
- None of these
Why implement From<ParseIntError> for your own error type?
- So it can be printed
- So
?can automatically convert a ParseIntError into your error - So it can be compared with ==
- It is required for every enum