Learn/Rust/9. Handling errors
Lesson 9 of 15
Sign in

Rust, lesson 9

Handling errors

Rust has no exceptions and no null. Instead, two ordinary enums from the standard library describe things that can go wrong, and the type system makes sure you deal with them.

  • Option<T> is either Some(value) or None. Use it when a value might simply be absent.
  • Result<T, E> is either Ok(value) or Err(error). Use it when an operation can fail and you want to say why.

You have already met both: vec.get(i) returns an Option, and "42".parse::<i32>() returns a .

2 exercises to try what you just read.

Exercise 1

Careful calculator

Press Ctrl Enter or Check to test your code.

Exercise 2

Coffee card

Press Ctrl Enter or Check to test your code.

Result

Handling with match

e here is a ParseIntError. Printing it with {} shows a readable message such as invalid digit found in string.

Because the compiler knows a Result might be an error, you cannot use the number inside until you have handled both cases. That is the whole idea: failure is visible in the type.

Shortcuts

Writing match every time gets long. Common helpers:

unwrap() and expect("message") take the value out or panic (stop the program) on Err or None. They are fine in quick experiments and when failure really is impossible, but real programs should handle errors instead.

Returning errors from your functions

Return a Result when your function can fail. The error type can be anything; a String is simplest to start with:

map_err converts one error into another, here a parse error into our own message.

The ? operator

The ? after an expression means: "if this is Ok, give me the value; if it is Err, return that error from the current function right now". It removes the boilerplate of passing errors upward, and it only works inside a function that itself returns Result (or Option for Option values).

When the error types differ, ? converts them using the From trait, so you can make your own error type accept other errors automatically.

Custom error enums

For errors that callers need to tell apart, define an enum and implement Display so it prints nicely:

Now callers can match on the variant to react differently, and print the error with {}. Lesson 10 covers enums and impl blocks in more detail.

panic! is for bugs

panic!("message") stops the program immediately. Use it for situations that mean the code itself is wrong, not for bad input from the outside world.

Further reading

  • The Rust Book: Recoverable errors with Result
  • The Rust Book: To panic! or not to panic!
  • std::result
  • std::option

Each input line holds a calculation: a number, an operator (+, -, * or /) and a number, separated by spaces. Write fn calc(line: &str) -> Result<i64, String> and print the result for each line. When a line is invalid, print error: followed by the message and carry on. Messages:

  • not exactly 3 parts: need 3 parts
  • a number that does not parse: bad number "<text>"
  • division by zero: division by zero
  • any other operator: unknown operator "<op>"

Sample input:

Sample output:

A coffee card starts with 20 credits. Each input line is a purchase amount (a whole number, possibly negative). Using the CardError enum in the starter, write fn buy(balance: i64, cost: i64) -> Result<i64, CardError> that returns the new balance, or Err(CardError::BadAmount(cost)) when the cost is zero or negative, or Err(CardError::NoCredit) when the cost is larger than the balance.

In main, print ok, balance <b> on success. On failure print refused: <error> and keep the old balance; when the error is NoCredit, also print (top up your card) on the next line.

Sample input:

Sample output:

match "12a".parse::<i32>() {
    Ok(n) => println!("double: {}", n * 2),
    Err(e) => println!("bad number: {e}"),
}
let n: i32 = text.parse().unwrap_or(0);     // fall back to a default
let first = names.first().unwrap_or(&"nobody");
if let Ok(n) = text.parse::<i32>() {        // only care about success
    println!("{n}");
}
let Ok(n) = text.parse::<i32>() else {      // let-else: bail out on failure
    return;
};
fn parse_age(text: &str) -> Result<u32, String> {
    let age: u32 = text.trim().parse().map_err(|_| format!("not a number: {text}"))?;
    if age > 150 {
        return Err(format!("too old: {age}"));
    }
    Ok(age)
}
fn total_price(qty: &str, price: &str) -> Result<u32, String> {
    let q = parse_age(qty)?;  // returns early on error
    let p = parse_age(price)?;
    Ok(q * p)
}
use std::fmt;

enum CardError {
    NoCredit,
    BadAmount(i64),
}

impl fmt::Display for CardError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CardError::NoCredit => write!(f, "not enough credit"),
            CardError::BadAmount(n) => write!(f, "invalid amount {n}"),
        }
    }
}
6 * 7
10 / 0
4 x 2
seven + 1
42
error: division by zero
error: unknown operator "x"
error: bad number "seven"
4
5
15
-2
ok, balance 16
ok, balance 11
refused: not enough credit
(top up your card)
refused: invalid amount -2