Lesson 12 of 26
Result and ? instead of exceptions
In Python a function can fail without saying so. int("x") looks like any other call, then it
raises ValueError, and you find out by running it or by reading the docs. Rust puts the failure in
the return type: Result<T, E> means "either a value of type T, or an error of type E".
Result is an enum with two variants, like the enums in lesson 10:
Ok(value): it worked, here is the value.Err(error): it failed, here is the error.
So you can see which functions can fail just by reading their signature. You also cannot use the value
without opening the Result first, so nothing is silently ignored. Two tools open it:
match when you handle both cases here, and ? when you want the error to travel up to
the caller, the way an exception does.
Option<T> from lesson 11 is a close cousin: it is either Some(value) or
None, "a value or nothing". Result is "a value or an error", and the error can say what
went wrong.
panic! is the other kind of failure: it stops the whole program right there, like a
raise that nobody catches. You will see it in code that treats a bug as unrecoverable.
Parsing gives a Result, not an exception
int(text) and parse do the same job, but Rust hands the outcome back as a
value. match then takes it apart, one arm per variant.
for text in ["42", "4x2"]:
try:
n = int(text)
print(f"parsed {n}")
except ValueError:
print("not a number")fn main() {
for text in ["42", "4x2"] {
match text.parse::<i32>() {
Ok(n) => println!("parsed {n}"),
Err(_) => println!("not a number"),
}
}
}parsed 42
not a numberThe ? operator lets the error travel up
Python code often lets an exception bubble up through several functions, and catches it once at the
top. ? does exactly that, but the signatures show it.
Read ? as: "If this is an Err, return it from this function right now.
Otherwise give me the value inside the Ok."
The function must say in its return type that it can fail, otherwise ? does not compile.
def read_number(text):
n = int(text)
return n * 2
def read_label(text):
n = read_number(text)
return f"label-{n}"
for text in ["21", "x"]:
try:
print(read_label(text))
except ValueError:
print("failed")fn read_number(text: &str) -> Result<i32, std::num::ParseIntError> {
let n: i32 = text.parse()?;
Ok(n * 2)
}
fn read_label(text: &str) -> Result<String, std::num::ParseIntError> {
let n = read_number(text)?;
Ok(format!("label-{n}"))
}
fn main() {
for text in ["21", "x"] {
match read_label(text) {
Ok(label) => println!("{label}"),
Err(_) => println!("failed"),
}
}
}label-42
failedunwrap, expect and unwrap_or
.unwrap() says "I am sure this is Ok, give me the value". On an
Err it panics: the program stops and prints an error. That is the same as an exception you
never catch. .expect("message") does the same but adds your message to the crash.
Neither is a way to handle errors. You meet them everywhere while reading Rust, mostly in examples and in
code that has already checked the input. .unwrap_or(default) is the calm version: it uses a
fallback instead of crashing.
def to_number(text):
try:
n = int(text)
except ValueError:
raise ValueError("bad number")
return n + 1
good = int("7")
also = int("8")
try:
fallback = int("x")
except ValueError:
fallback = 0
print(good, also, fallback)
try:
print(to_number("x"))
except ValueError as e:
print(e)fn to_number(text: &str) -> Result<i32, String> {
let n: i32 = text.parse().map_err(|_| String::from("bad number"))?;
Ok(n + 1)
}
fn main() {
let good: i32 = "7".parse().unwrap();
let also: i32 = "8".parse().expect("8 is a number");
let fallback: i32 = "x".parse().unwrap_or(0);
println!("{good} {also} {fallback}");
match to_number("x") {
Ok(n) => println!("{n}"),
Err(msg) => println!("{msg}"),
}
}7 8 0
bad numberYour own error type is an enum
Standard errors like ParseIntError are fine until you need to say why something failed.
Then you write an enum, exactly like lesson 10, and use it as the E in Result. Each
variant is one kind of failure, and a variant can carry data.
class BadName(Exception):
pass
def check_name(name):
if not name:
raise BadName("empty name")
if len(name) > 5:
raise BadName(f"too long: {len(name)} letters")
return name.upper()
for name in ["ada", "", "lovelace"]:
try:
print(f"ok {check_name(name)}")
except BadName as e:
print(e)#[derive(Debug)]
enum BadName {
Empty,
TooLong(usize),
}
fn check_name(name: &str) -> Result<String, BadName> {
if name.is_empty() {
return Err(BadName::Empty);
}
if name.len() > 5 {
return Err(BadName::TooLong(name.len()));
}
Ok(name.to_uppercase())
}
fn main() {
for name in ["ada", "", "lovelace"] {
match check_name(name) {
Ok(n) => println!("ok {n}"),
Err(BadName::Empty) => println!("empty name"),
Err(BadName::TooLong(n)) => println!("too long: {n} letters"),
}
}
}ok ADA
empty name
too long: 8 lettersmain can return a Result too
fn main() may itself return a Result. Then you can use ? at the top
level of the program, and no match is needed. On success, main must end with
Ok(()).
The catch: if a ? really returns an Err, the program stops and exits with an error
status. That is fine for a command-line tool, and it is what you will see in real code.
When there is more than one error type in one function, you will see
Box<dyn std::error::Error> as the error type. Read it as "any error".
try:
count = int("3")
price = float("2.5")
print(f"{count} items at {price} = {count * price}")
except ValueError as e:
print(f"error: {e}")fn main() -> Result<(), Box<dyn std::error::Error>> {
let count: i32 = "3".parse()?;
let price: f64 = "2.5".parse()?;
println!("{count} items at {price} = {}", count as f64 * price);
Ok(())
}3 items at 2.5 = 7.5Where the Python analogy breaks
- Errors are values, not jumps. A Rust function that can fail returns a
Result, and the caller has to deal with it. Nothing travels up the call stack by itself unless you write?. ?only works inside a function that returnsResult(orOption), and the error types must fit. In Python any function can raise anything.- There's no
finallyand nowith. Cleanup happens when a value goes out of scope: a file closes at the}where its variable ends, even after an earlyreturnor?. - A panic is not an exception.
panic!,unwrap()andexpect()are for bugs and "can't happen" cases, not normal error handling. UseResultfor errors you expect, like bad input.
Cheat card
| Python | Rust |
|---|---|
try:
n = int(s)
except ValueError:
n = 0 | let n: i32 = s.parse().unwrap_or(0); |
n = int(s) # may raise | let n: i32 = s.parse::<i32>()?; |
raise ValueError("empty") | return Err(BadName::Empty); |
x = f() # may raise | let x = f()?; |
try:
print(f())
except ValueError as e:
print(e) | match f() {
Ok(v) => println!("{v}"),
Err(e) => println!("{e}"),
} |
n = int(s) # crashes on bad input | let n: i32 = s.parse::<i32>().unwrap(); |
n = int(s) # crashes, with a message | let n: i32 = s.parse().expect("need a number"); |
raise RuntimeError("boom") | panic!("boom"); |
def f() -> int: | fn f() -> Result<i32, ParseIntError> |
def f() -> None: # may fail | fn f() -> Result<(), String> |
x if x is not None else 0 | x.unwrap_or(0) |