Error Handling (Result & ? Operator)
Rust does not support try-catch exceptions. Instead, errors are returned explicitly as variants of the Result enum, enabling robust error handling at compile time.
1 Result enum & The ? operator propagation
Recoverable errors in Rust return the built-in **`Result<T, E>`** enum:
- `Ok(value)`: The operation succeeded, returning the value.
- `Err(error)`: The operation failed, returning the error details.
The ? Operator: Writing **`?`** after a Result expression automatically returns the error to the caller function if the operation fails, dramatically simplifying error propagation syntax.
2 Error Handling Code
Let's run a program illustrating Result handling and error propagation using the ? operator:
Rust — Result error checking
▶ Run Code
fn divide(x: f64, y: f64) -> Result {
if y == 0.0 {
return Err(String::from("Division by zero error."));
}
Ok(x / y)
}
fn calculate() -> Result {
// The '?' operator automatically returns the error if divide fails
let value = divide(10.0, 0.0)?;
Ok(value * 2.0)
}
fn main() {
match calculate() {
Ok(result) => println!("Calculation Result: {}", result),
Err(err) => println!("Error Caught: {}", err),
}
}
3 Code Challenge
Challenge: Write a custom function called `parse_number` that takes a string slice and returns a `Result`. If the string cannot be parsed as an integer, return a descriptive error message.