rustHow to catch error in Rust
Rust provides a number of ways to catch errors. The most common way is to use the Result type. Result is an enum that can either be Ok or Err. Ok is used to indicate success and Err is used to indicate an error.
Code example:
fn main() {
let result = divide(4, 2);
match result {
Ok(val) => println!("Result: {}", val),
Err(e) => println!("Error: {}", e),
}
}
fn divide(x: i32, y: i32) -> Result<i32, &'static str> {
if y == 0 {
return Err("Cannot divide by 0");
}
Ok(x / y)
}
Output
Result: 2
Explanation:
- The
dividefunction takes twoi32parameters and returns aResulttype. - The
Resulttype is an enum that can either beOkorErr. - If the
yparameter is 0, theErrvariant is returned with an error message. - If the
yparameter is not 0, theOkvariant is returned with the result of the division. - The
matchstatement is used to check theResulttype and print the appropriate message. - If the
ResultisOk, the value is printed. - If the
ResultisErr, the error message is printed.
Helpful links:
More of Rust
- How to use regex lookahead in Rust?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- How to replace all matches using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use negation in Rust regex?
- How to perform matrix operations in Rust?
- How to match a URL with a regex in Rust?
See more codes...