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 match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- How to make regex case insensitive in Rust?
- How to use non-capturing groups in Rust regex?
- How to yield a thread in Rust?
- Using bool in enum in Rust
- How to use regex captures in Rust?
See more codes...