try and catch in rust

fn main() {
    let result = divide(10, 0);
    match result {
        Ok(value) => println!("Result: {}", value),
        Err(err) => println!("Error: {}", err),
    }
}

fn divide(a: i32, b: i32) -> Result<i32, &'static str> {
    if b == 0 {
        return Err("Division by zero");
    }
    Ok(a / b)
}

Explanation:

  1. The main function is the entry point of the Rust program.
  2. Inside main, it calls the divide function with the values 10 and 0, assigning the result to the result variable.
  3. The divide function takes two parameters (a and b) and returns a Result type, where the success case holds an i32 value and the error case holds a &'static str (a static string).
  4. Inside divide, it checks if b is equal to 0. If it is, it returns an Err variant with the message "Division by zero".
  5. If b is not 0, it performs the division a / b and returns an Ok variant containing the result.

  6. After calling divide in main, the match statement is used to pattern match against the result.

  7. If result is Ok, it prints the result value using println!.
  8. If result is Err, it prints the error message using println!.