Rust Error Handling
Error Handling
In the previous chapter, a panic stopped the whole program. But many errors are expected, and the program should be able to continue. For example, a user can type "hello" where the program expects a number.
For errors like this, Rust uses an enum called Result. It works like Option, but instead of Some and None, it has these two variants:
Ok(value)- it worked, and here is the valueErr(error)- something went wrong, and here is the error
For example, the parse() method turns text into a number. parse::<i32>() means "turn this text into an i32". It returns a Result, because the text might not be a number:
Example
let good = "42".parse::<i32>();
let bad = "hello".parse::<i32>();
println!("{:?}", good); // Ok(42)
println!("{:?}", bad); // Err(ParseIntError { kind: InvalidDigit })
Try it Yourself »
"42" can be turned into a number, so the result is Ok(42). "hello" cannot, so the result is an Err, which tells you why: the text has an invalid digit.
Check the Result With match
Just like with Option, you can use match to handle both cases:
Example
let text = "abc";
match text.parse::<i32>() {
Ok(number) => println!("The number is {}", number),
Err(e) => println!("Error: {}", e),
}
Try it Yourself »
The text "abc" is not a number, so the Err branch runs and prints the error message: invalid digit found in string. The program does not crash. It continues after the match.
Return a Result From a Function
Your own functions can also return a Result. In Result<i32, String>, i32 is the type of the value when it works (Ok), and String is the type of the error (Err):
Example
fn buy(coins: i32, price: i32) -> Result<i32, String> {
if price > coins {
Err(String::from("Not enough coins"))
} else {
Ok(coins - price)
}
}
fn main() {
match buy(100, 30) {
Ok(left) => println!("You bought it! Coins left: {}", left),
Err(e) => println!("Error: {}", e),
}
match buy(20, 30) {
Ok(left) => println!("You bought it! Coins left: {}", left),
Err(e) => println!("Error: {}", e),
}
}
Try it Yourself »
With 100 coins, you can buy an item that costs 30, so the function returns Ok(70). With only 20 coins, it returns an Err with the message "Not enough coins".
Use a Default Value
Like with Option, you can use unwrap_or() to get the value, or a default value if there is an error:
Example
let a = "42".parse::<i32>().unwrap_or(0);
let b = "hello".parse::<i32>().unwrap_or(0);
println!("a = {}", a); // 42
println!("b = {}", b); // 0
Try it Yourself »
unwrap() and expect()
The unwrap() method gives you the value inside Ok directly:
Example
let number = "42".parse::<i32>().unwrap();
println!("{}", number + 1); // 43
Try it Yourself »
But if the result is an Err, unwrap() panics and stops the program:
Example
let number = "hello".parse::<i32>().unwrap(); // Error
println!("{}", number + 1);
Try it Yourself »
The expect() method works the same way, but lets you write your own error message. This makes it easier to find out what went wrong:
Example
let number = "hello".parse::<i32>().expect("The text must be a whole number");
println!("{}", number + 1);
Try it Yourself »
Note: Only use unwrap() and expect() when you are sure that there is no error, or in small test programs. In other cases, handle the error with match or unwrap_or().
The ? Operator
When a function calls other functions that return a Result, checking each result with match can make the code long. The ? operator is a shortcut:
- If the result is
Ok,?gives you the value inside, and the code continues - If the result is
Err,?stops the function right away, and returns the error
Example
use std::num::ParseIntError;
fn add_numbers(a: &str, b: &str) -> Result<i32, ParseIntError> {
let x = a.parse::<i32>()?;
let y = b.parse::<i32>()?;
Ok(x + y)
}
fn main() {
println!("{:?}", add_numbers("10", "20"));
println!("{:?}", add_numbers("10", "abc"));
}
Try it Yourself »
ParseIntError is the error type that parse() returns when the text is not a whole number. It is imported with use at the top, just like HashMap.
In the second call, "abc" cannot be turned into a number, so ? returns the error, and Ok(x + y) is never reached.
Note: You can only use ? inside a function that returns a Result (or an Option).
Summary
| Code | What it does |
|---|---|
match |
Handles Ok and Err in different ways |
unwrap_or(value) |
Gives the value, or a default value if there is an error |
? |
Gives the value, or returns the error from the function |
unwrap() and expect() |
Gives the value, but panics if there is an error |