Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lecture 13 - Errors: Result, Option, and reading a file

A path forking, one branch continuing and the other ending in a cross

Announcements




Learning objectives

By the end of today, you should be able to:

  • Say what panic! does, and call it directly or through unwrap and expect
  • Decide when to panic and when to return a Result, and defend the choice
  • Write a function that returns Result<T, E> and handle both cases at the call site
  • Use match and ? to handle an error or pass it up
  • Read a file and write a file, and deal with the Result each one hands back

Part 1: A program that needs all this

So you want to read a file

Your data is in a file. You want it in a String. This should be one line:

fn main() {
    let text = std::fs::read_to_string("data.csv");
    println!("{}", text);
}

It does not compile.

The compiler says what you actually got

error[E0277]: `Result<String, std::io::Error>` doesn't implement `std::fmt::Display`
 --> src/main.rs:3:20
  |
3 |     println!("{}", text);
  |               --   ^^^^ `Result<String, std::io::Error>` cannot be formatted

You asked for a String. You got a Result<String, std::io::Error>.

The value you wanted, inside a box you have to open

Rust will not let you use the text until you have said what happens when there is no text.

That is the whole lecture. Every language has this problem. Rust is the one that makes you answer it before the program runs.

Rust's Error Philosophy: Errors as Data

Most languages: Errors are "exceptional" events that get thrown and caught

try:
    result = divide(a, b)
    # continue with result
except DivisionByZeroError:
    # handle error

Rust: Errors are just another kind of data that functions can return

match divide(a, b) {
    Ok(result) => { /* continue with result */ },
    Err(error) => { /* handle error */ },
}

Error Handling in Rust

Two basic options:

  • terminate when an error occurs: macro panic!(...)
  • pass information about an error: enum Result<T,E>

Option 1: Choose to panic!

What it means to panic:

  • stops execution ("crashes")
  • starts "unwinding the stack" (more on that later)
  • prints a message to the console
  • tells us where in the code the panic occurred

Macro panic!(...)

  • Use for unrecoverable errors
fn divide(a:u32, b:u32) -> u32 {
    if b == 0 {
        panic!("I'm sorry, Dave. I'm afraid I can't do that.");
    }
    a/b
}

fn main() {
    println!("{}",divide(20,7));
    // println!("{}",divide(20,0));
}

Getting more info out of a panic!

  • Use RUST_BACKTRACE=1 cargo run to get a backtrace like this:
$ RUST_BACKTRACE=1 cargo run
thread 'main' panicked at src/main.rs:4:6:
index out of bounds: the len is 3 but the index is 99
stack backtrace:
   0: rust_begin_unwind
             at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/std/src/panicking.rs:692:5
   1: core::panicking::panic_fmt
             at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:75:14
   2: core::panicking::panic_bounds_check
             at /rustc/4d91de4e48198da2e33413efdcd9cd2cc0c46688/library/core/src/panicking.rs:273:5
   3: <usize as core::slice::index::SliceIndex<[T]>>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:274:10
   4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/slice/index.rs:16:9
   5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/alloc/src/vec/mod.rs:3361:9
   6: panic::main
             at ./src/main.rs:4:6
   7: core::ops::function::FnOnce::call_once
             at file:///home/.rustup/toolchains/1.85/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

Shortcuts to panic!

Both unwrap and expect will call panic! if there is an error.

use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt").unwrap();
println!("{:?}", greeting_file);
}
use std::fs::File;
fn main() {
let greeting_file = File::open("hello.txt")
        .expect("hello.txt should be included in this project");
println!("{:?}", greeting_file);
}

expect takes a message and unwrap does not, which is the whole difference. Write what you assumed, not what broke: "hello.txt should be included in this project" tells whoever reads the crash why the assumption was wrong. That is usually you, three weeks later.

Quick Quiz

1. Which #[derive()] trait lets you print an enum with {:?}?

2. Why won't this compile?

#![allow(unused)]
fn main() {
enum Status {
    Loading,
    Complete,
    Error,
}

let status = Status::Complete;
match status {
    Status::Complete => println!("Finished!"),
    Status::Error => println!("An error has occurred!"),
}
}

3. What do you think this will print?

#![allow(unused)]
fn main() {
let result = Some(42);
match result {
    Some(x) if x > 40 => println!("Large: {}", x),
    Some(x) => println!("Small: {}", x),
    None => println!("Nothing"),
}
}

Recap: Option<T>

Wednesday's problem: Python's find_index returns -1 for a missing name, and last_names[-1] quietly prints the wrong person.

Rust's answer is a built-in enum with two variants:

enum Option<T> {
    Some(T),
    None,
}
  • Some(T) holds the value
  • None means there isn't one, and that is a normal answer, not a failure
  • You can't use the value until you've opened it, and match makes you say what happens on None
match find_index("Totoro", names) {
    Some(i) => println!("{} {}", "Totoro", last_names[i]),
    None => println!("Totoro is not in the list"),
}

Option<T>: useful methods

match always works, but a few methods cover the common cases in one line.

Check the variant

  • .is_some() -> bool
  • .is_none() -> bool

Get the value in Some, or a default if there isn't one

  • .unwrap_or(default_value: T) -> T
fn find_index(target: &str, names: [&str; 3]) -> Option<usize> {
    for i in 0..names.len() {
        if target == names[i] {
            return Some(i);
        }
    }
    None
}
fn main() {
    let names = ["Kesar", "Mei", "Satsuki"];
    let found = find_index("Mei", names);
    let missing = find_index("Totoro", names);

    println!("{} {}", found.is_some(), missing.is_some());
    println!("{}", missing.is_none());
    println!("{} {}", found.unwrap_or(99), missing.unwrap_or(99));
}
true false
true
1 99

unwrap and expect work on Option too

Same two methods as on the panic! slide, and they panic the same way. Option says there might be nothing; unwrap is you saying there is:

fn find_index(target: &str, names: [&str; 3]) -> Option<usize> {
    for i in 0..names.len() {
        if target == names[i] {
            return Some(i);
        }
    }
    None
}
fn main() {
    let names = ["Kesar", "Mei", "Satsuki"];
    println!("{}", find_index("Mei", names).unwrap());
    println!("{}", find_index("Totoro", names).expect("Totoro should be in the list"));
}
1
thread 'main' panicked at src/main.rs:13:48:
Totoro should be in the list

Option can tell you there's nothing. It can't tell you why. When the caller needs the why, you want Result.

Enum Result<T,E>

enum Result<T,E> {
    Ok(T),
    Err(E),
}

Functions can use it to

  • return a result
  • or information about an encountered error
fn divide(a:u32, b:u32) -> Result<u32, String> {
    if b != 0 {
        Ok(a / b)
    } else {
        let str = format!("Division by zero {} {}", a, b);
        Err(str)
    }
}

fn main(){
    println!("{:?}",divide(20,7));
    // println!("{:?}",divide(20,0));
}

Opening a Result

Ok and Err are variants, so match gets the value back out. This is the skeleton from the start of class, filled in:

fn divide(a: u32, b: u32) -> Result<u32, String> {
    if b != 0 {
        Ok(a / b)
    } else {
        let str = format!("Division by zero {} {}", a, b);
        Err(str)
    }
}
fn main() {
    match divide(20, 7) {
        Ok(answer) => println!("got {}", answer),
        Err(message) => println!("failed: {}", message),
    }

    match divide(20, 0) {
        Ok(answer) => println!("got {}", answer),
        Err(message) => println!("failed: {}", message),
    }
}
got 2
failed: Division by zero 20 0

Neither call crashed! The second one failed, explained why, and let the program keep going. That is the whole difference between handing back a Result and calling panic!.

parse hands back a Result too

Remember parse? It also returns a Result to handle cases when parse... can't.

fn main() {
    match "42".parse::<i32>() {
        Ok(number) => println!("got {}", number),
        Err(problem) => println!("failed: {}", problem),
    }

    match "4x2".parse::<i32>() {
        Ok(number) => println!("got {}", number),
        Err(problem) => println!("failed: {}", problem),
    }
}
got 42
failed: invalid digit found in string

Same shape as the last slide, different function. The ::<i32> says which type to aim for, since parse can produce plenty of them.

When to use Option<T>, Result<T,E>, and panic!

  • Use Option<T> when there might be nothing, and nothing is a normal answer: the name is not in the list
  • Use Result<T,E> when you want to handle the error and continue execution, and the caller deserves to know what went wrong: the file is not there
  • Use panic! when the error is unrecoverable

The tell between the first two: if you have to invent an error message to explain the empty case, you wanted Option. If you already have one, you wanted Result.

Concept: Propagating Errors

Error propagation means passing errors up through layers of function calls.

Think of it like a company hierarchy:

  • Junior developer encounters a bug they can't fix, reports it to senior developer
  • Senior dev can't solve it, escalates to team lead
  • Each level decides: "Can I handle this?" or "Pass it up the chain"

Or like the court system:

  • Local court -> Appeals court -> State supreme court -> Federal supreme court
  • Each level can either handle the case or pass it to a higher authority

Different jobs for different functions:

  • Low-level functions know what went wrong, but not what to do about it
  • High-level functions have context to decide how to respond to different errors

Propagating errors in Rust

  • We are interested in the positive outcome: t in Ok(t)
  • But if an error occurs, we want to propagate it ("pass the buck")
  • This can be handled using match statements

An error traveling back up the call stack

// compute a/b + c/d
fn calculate(a:u32, b:u32, c:u32, d:u32) -> Result<u32, String> {
    let first = match divide(a,b) {
        Ok(t) => t,
        Err(e) => return Err(e),
    };
    let second = match divide(c,d) {
        Ok(t) => t,
        Err(e) => return Err(e),
    };
    Ok(first + second)
}

fn divide(a:u32, b:u32) -> Result<u32, String> {
    if b != 0 {
        Ok(a / b)
    } else {
        let str = format!("Division by zero {} {}", a, b);
        Err(str)
    }
}

fn main(){
    println!("{:?}", calculate(16,4,18,3));
    println!("{:?}", calculate(16,0,18,3));
}

return inside an arm returns from the whole function, not from the match. The Err arm never hands a value back to let first, because by then we are already gone.

The question mark shortcut

  • Place ? after an expression that returns Result<T,E>

  • This will:

    • give the content of Ok(t)
    • or return Err(e) from the encompassing function

The two exits of the question mark operator

fn calculate(a:u32, b:u32, c:u32, d:u32) -> Result<u32, String> {
    Ok(divide(a,b)? + divide(c,d)?)
}

fn divide(a:u32, b:u32) -> Result<u32, String> {
    if b != 0 {
        Ok(a / b)
    } else {
        let str = format!("Division by zero {} {}", a, b);
        Err(str)
    }
}

fn main(){
    println!("{:?}", calculate(16,4,18,3));
    println!("{:?}", calculate(16,0,18,3));
}

Caution with ?

The ? operator can only be used in functions whose return type is compatible with the value the ? is used on.

  • If you use ? on a Result<T,E>, the function must return Result<..., E> (with the same E!)
  • If you use ? on an Option<T>, the function must return Option<...>.

Back to reading a file...

use std::fs;

fn main() {
    match fs::read_to_string("data.csv") {
        Ok(text) => println!("read {} bytes", text.len()),
        Err(e) => println!("could not read it: {}", e),
    }

    fs::write("out.txt", "hello from Rust\n").expect("could not write out.txt");
}

fs::read_to_string gives you the whole file as a String. fs::write puts a string in a file, creating it or replacing what was there.

Both hand back a Result, because both can fail.

read_to_string reads the whole file into memory at once. Fine for a homework CSV, a bad idea for a 40GB log. Lecture 36 covers reading a line at a time.

Activity Time

On paper, on your own. Put your name on the sheet and hand it in at the end.

See Activity 13