2.11 Error Handling
2.11.1 Result
and Option
Types
Rust does not use exceptions for error handling. Instead, it uses the Result
and Option
types.
fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { Err(String::from("Cannot divide by zero")) } else { Ok(a / b) } } fn main() { match divide(4.0, 2.0) { Ok(result) => println!("Result is {}", result), Err(e) => println!("Error: {}", e), } }
2.11.2 Comparison with C
C typically handles errors using return codes and errno
.
#include <stdio.h>
#include <errno.h>
#include <math.h>
int divide(double a, double b, double *result) {
if (b == 0.0) {
errno = EDOM; // Domain error
return -1;
} else {
*result = a / b;
return 0;
}
}
int main() {
double res;
if (divide(4.0, 0.0, &res) != 0) {
perror("Error");
} else {
printf("Result is %f\n", res);
}
return 0;
}