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 match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to clear a Rust HashMap?
- Yield example in Rust
- Example of yield_now in Rust?
- How to convert a Rust slice to a fixed array?
- How to use regex to match a group in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to yield a thread in Rust?
- How to replace strings using Rust regex?
See more codes...