Start learning free

LESSON 616 OF 642 · OBJECT-ORIENTED PROGRAMMING

Errors and Exceptions in Rust in Rust

Lesson

TL ; DR:

Rust has no exceptions. A function that can fail returns a Result: Ok with the value, or Err with the error. The caller handles both with match.


fn spend(&mut self, amount: i32) -> Result<i32, String> {
    if amount > self.money {
        return Err(String::from("not enough money"));
    }

    self.money -= amount;
    Ok(self.money)
}

match wallet.spend(80) {
    Ok(left) => println!("{} left", left),
    Err(message) => println!("error: {}", message),
}


Full lesson:

Some requests can't be done. A wallet with 50 can't spend 80.

The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.

Many languages throw an exception here. Rust doesn't. Its result type says that the call can fail.

Returning a Result

  • Result<i32, String> is one of two things.
  • Ok(v) holds the value v, an i32 here.
  • Err(e) holds the error e, a String here.
  • return Err(...) stops the method. So the wallet keeps its money.
  • The last line, Ok(self.money), is the result when all went well.

Handling it

  • A match on the result has one arm for each case.
  • Ok(left) unpacks the value into left.
  • Err(message) unpacks the error into message.
  • The compiler wants both arms. So an error can't be forgotten.

It works like Option, which you met before. Ok and Err take the place of Some and None.


Your task

A Wallet starts with 50. Its spend method takes money out and returns what is left.

  • In spend, return an Err when amount is more than self.money. Its message is "not enough money".
  • In the loop, match the result of spend.
  • On Ok(left), print what was spent and what is left. On Err(message), print error: and the message.

The loop tries to spend 20, then 40, then 30.

Expected output:

spent 20, 30 left
error: not enough money
spent 30, 0 left
STEP 1 OF 3
    Ctrl + Enter to check

    Raising Errors in Rust

    Keep going with Rust500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free