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 replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex captures in Rust?
- How to ignore case in Rust regex?
- How to perform matrix operations in Rust?
- How to use regex to match a double quote in Rust?
- Regex example to match multiline string in Rust?
- How to make regex case insensitive in Rust?
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
See more codes...