23.08 Error Handling

Error Handling

Overview

Rust uses Result and Option enums for error handling, ensuring safe and explicit error management.

Topics

Examples

fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Errfrom("Cannot divide by zero")
    } else {
        Ok(a / b)
    }
}

match divide(10, 2) {
    Ok(result) => println!("Result: {}", result),
    Err(e) => println!("Error: {}", e),
}

let maybe_value: Option<i32> = Some(5);
if let Some(value) = maybe_value {
    println!("Value: {}", value);
}

Tags

#rust #errorhandling #result #option