rustUsing error chain in Rust
Error chain is a Rust library for creating and managing error types and error handling. It provides a convenient way to define and propagate errors throughout a Rust program.
Code example:
use error_chain::error_chain;
error_chain! {
foreign_links {
Io(std::io::Error);
ParseInt(std::num::ParseIntError);
}
}
fn main() -> Result<()> {
let result = std::fs::read_to_string("my_file.txt")?;
let number = result.parse::<i32>()?;
println!("Number is {}", number);
Ok(())
}
Output
Number is 42
Explanation:
- The
error_chain!
macro is used to define the error types and foreign links. - The
foreign_links
section defines the external errors that can be propagated through the error chain. In this example,std::io::Error
andstd::num::ParseIntError
are defined as foreign links. - The
main
function is used to read a file and parse its contents as an integer. - The
std::fs::read_to_string
function is used to read the contents of the file into a string. The?
operator is used to propagate any errors that occur during the read operation. - The
parse::<i32>
method is used to parse the string as an integer. The?
operator is used to propagate any errors that occur during the parse operation. - The parsed integer is printed to the console.
- The
Ok(())
expression is used to indicate that the function has completed successfully.
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...