RicardasSim

Basic error handling in Rust with Ok and Err(e)

Nov 14th, 2026
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.02 KB | None | 0 0
  1. /*
  2.     Demonstrates basic error handling in Rust using
  3.     the `Result` enum with `Ok` and `Err(e)`.
  4. */
  5.  
  6. /// Divides two `f64` numbers and returns a `Result`:
  7. /// - `Ok(f64)` if the division succeeds
  8. /// - `Err(String)` if attempting to divide by zero
  9. fn divide(dividend: f64, divisor: f64) -> Result<f64, String> {
  10.     if divisor == 0.0 {
  11.         // Return an error wrapped in `Err`
  12.         Err(String::from("Cannot divide by zero!"))
  13.     } else {
  14.         // Return a successful value wrapped in `Ok`
  15.         Ok(dividend / divisor)
  16.     }
  17. }
  18.  
  19. fn main() {
  20.     // 1. Success case (returns `Ok`)
  21.     let result_1 = divide(10.0, 2.0);
  22.     match result_1 {
  23.         Ok(value) => println!("Success! Answer: {}", value),
  24.         Err(e) => println!("Error: {}", e),
  25.     }
  26.  
  27.     println!("----------------");
  28.  
  29.     // 2. Error case (returns `Err(e)`)
  30.     let result_2 = divide(10.0, 0.0);
  31.     match result_2 {
  32.         Ok(value) => println!("Success! Answer: {}", value),
  33.         Err(e) => println!("Error: {}", e),
  34.     }
  35. }
  36.  
Advertisement
Add Comment
Please, Sign In to add comment