w3resource

Rust Function: Safe Division with Error handling

Rust Handling Errors with Result and Option: Exercise-5 with Solution

Write a Rust function that divides two numbers and prints the result or an error message if division by zero occurs.

Sample Solution:

Rust Code:

fn divide(x: f64, y: f64) {
    if y == 0.0 {
        println!("Error: Division by zero!");
    } else {
        let result = x / y;
        println!("Result: {}", result);
    }
}

fn main() {
    let numerator = 10.0;
    let denominator = 0.0;
    divide(numerator, denominator);
}

Output:

Error: Division by zero!

Explanation:

Here's a brief explanation of the above Rust code:

  • The "divide()" function takes two f64 parameters, 'x' (numerator) and 'y' (denominator).
  • It checks if the denominator is zero. If it is, it prints an error message.
  • If the denominator is not zero, it performs the division and prints the result.
  • In the "main()" function, we demonstrate calling the "divide()" function with a numerator of 10.0 and a denominator of 0.0, resulting in a division by zero error.

Rust Code Editor:

Previous: Rust Program: Count Lines in File with Error Handling.
Next: Rust Date Parser: Handling user input and Parsing errors.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/error_handling/rust-handling-errors-with-result-and-option-exercise-5.php