WeCodeAcademy

Rust Error Handling

Rust uses the Result type for operations that can fail. The ? operator passes an error up to the caller.

ExampleRust
use std::num::ParseIntError;

fn parse_double(s: &str) -> Result<i32, ParseIntError> {
    let n: i32 = s.trim().parse()?;
    Ok(n * 2)
}

fn main() {
    println!("{:?}", parse_double("21"));
    match parse_double("abc") {
        Ok(n) => println!("got {}", n),
        Err(e) => println!("error: {}", e),
    }
    let v: Option<i32> = None;
    println!("{}", v.unwrap_or(0));
}
Output
Ok(42)
error: invalid digit found in string
0
Quick check

What does the ? operator do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.