Lesson 11

Error Handling

Handle recoverable and unrecoverable errors in a clear Rust style.

Learning objectives

Two Kinds of Errors

Rust separates errors into unrecoverable errors and recoverable errors. Unrecoverable errors can use panic, while recoverable errors are usually represented with Result.

Result

Result has two common variants: Ok for success and Err for failure. This encourages you to handle errors instead of ignoring them.

Handling Errors

You can use match to handle both Ok and Err cases explicitly.

Example code

fn divide(a: f64, b: f64) -> Result<f64, String> {
    if b == 0.0 {
        Err(String::from("Cannot divide by zero"))
    } else {
        Ok(a / b)
    }
}

fn main() {
    match divide(10.0, 2.0) {
        Ok(value) => println!("Answer: {}", value),
        Err(message) => println!("Error: {}", message),
    }
}
Practice task: Write a function that returns Result and checks whether a mark is between 0 and 100.