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
divide
function takes twoi32
parameters and returns aResult
type. - The
Result
type is an enum that can either beOk
orErr
. - If the
y
parameter is 0, theErr
variant is returned with an error message. - If the
y
parameter is not 0, theOk
variant is returned with the result of the division. - The
match
statement is used to check theResult
type and print the appropriate message. - If the
Result
isOk
, the value is printed. - If the
Result
isErr
, the error message is printed.
Helpful links:
More of Rust
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to match whitespace with a regex in Rust?
- How to get an entry from a HashSet in Rust?
- How to replace a capture group using Rust regex?
- How to remove an element from a Rust HashMap if a condition is met?
- How to parse a file with Rust regex?
- How to match a URL with a regex in Rust?
- How to sort a Rust HashMap?
- How to replace all matches using Rust regex?
See more codes...