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 get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match the end of a line in a Rust regex?
- Hashshet example in Rust
- How to create a new Rust HashMap with values?
- How do I use a variable from another file in Rust?
- How to get the length of a Rust HashMap?
- How to get an element from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
See more codes...