w3resource

Rust Complex Calculation Error handling

Rust Error Propagation: Exercise-7 with Solution

Write a Rust function that performs complex calculations, handling errors related to invalid inputs or computational errors.

Sample Solution:

Rust Code:

// Define a function to perform complex calculations
fn complex_calculation(x: f64, y: f64) -> Result<f64, String> {
    // Check if any input is NaN (Not a Number)
    if x.is_nan() || y.is_nan() {
        // Return an error if any input is NaN
        return Err(String::from("Invalid input: NaN is not allowed"));
    }

    // Perform the complex calculation
    let result = x.powf(y);

    // Check if the result is infinite
    if result.is_infinite() {
        // Return an error if the result is infinite
        return Err(String::from("Computational error: Result is infinite"));
    }

    // Return the result if no errors occurred
    Ok(result)
}

// Define the main function
fn main() {
    // Test the complex_calculation function with valid inputs
    match complex_calculation(3.0, 2.0) {
        Ok(result) => println!("Result: {}", result),
        Err(err) => eprintln!("Error: {}", err),
    }

    // Test the complex_calculation function with invalid inputs (NaN)
    match complex_calculation(0.0, f64::NAN) {
        Ok(result) => println!("Result: {}", result),
        Err(err) => eprintln!("Error: {}", err),
    }

    // Test the complex_calculation function with computational error (result is infinite)
    match complex_calculation(100.0, 10000.0) {
        Ok(result) => println!("Result: {}", result),
        Err(err) => eprintln!("Error: {}", err),
    }
}

Output:

Error: Invalid input: NaN is not allowed
Error: Computational error: Result is infinite

Note: 
The output shows that the error message "Error: Invalid input: NaN is not allowed" is printed instead. This suggests that there might be an issue with how the input values are handled or passed to the function.

The error message "Invalid input: NaN is not allowed" indicates that at least one of the input values ('x' or 'y') is 'NaN' (Not a Number). This could happen if there's an issue with how the input values are initialized or modified before being passed to the "complex_calculation()" function.

Explanation:

Here is a brief explanation of the above Rust code:

  • complex_calculation Function:
    • It takes two parameters 'x' and 'y', both of type 'f64' (64-bit floating-point numbers).
    • It returns a Result<f64, String>, indicating either a successful result (Ok(f64)) or an error (Err(String)).
    • Inside the function:
      • It checks if either 'x' or 'y' is 'NaN' (Not a Number). If so, it returns an error with a message "Invalid input: NaN is not allowed".
      • It performs a complex calculation using the "powf()" method, raising 'x' to the power of 'y'.
      • It checks if the result is infinite using the "is_infinite()" method. If so, it returns an error with a message "Computational error: Result is infinite".
      • If no errors occur, it returns the calculated result.
  • main Function:
    • It tests the "complex_calculation()" function with different input scenarios using pattern matching (match).
    • In the first test, it calls complex_calculation(3.0, 2.0) with valid inputs and prints the result if successful. If an error occurs, it prints the error message.
    • In the second test, it calls complex_calculation(0.0, f64::NAN) with one input being 'NaN' and prints the error message.
    • In the third test, it calls complex_calculation(100.0, 10000.0) with inputs that lead to a computational error (resulting in infinity) and prints the error message.

Rust Code Editor:

Previous: Rust user input validation: Efficient error propagation.
Next: Rust System Calls and Error handling.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.