Rust’s error handling system is based on the Result type, which is an enum with two variants:
- ‘Ok(value)‘, which represents a successful result with a value.
- ‘Err(error)‘, which represents a failed result with an error.
When a function can fail, it returns a ‘Result<T, E>‘ type where ‘T‘ is the successful result type, and ‘E‘ is the error type.
Here’s an example of how to handle errors in Rust using the Result type:
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
fn read_file_lines(file_path: &str) -> Result<Vec<String>, io::Error> {
let file = File::open(file_path)?;
let reader = BufReader::new(file);
let lines = reader.lines().map(|line| line.unwrap()).collect();
Ok(lines)
}
fn main() -> Result<(), io::Error> {
let file_path = "my_file.txt";
let lines = read_file_lines(file_path)?;
for line in lines {
println!("{}", line);
}
Ok(())
}
In this example, ‘read_file_lines‘ is a function that reads all lines from a file and returns them as a vector of strings. The function returns a ‘Result<Vec<String>, io::Error>‘ type, where ‘Vec<String>‘ is the successful result type, and ‘io::Error‘ is the error type.
Inside the function, we open the file using ‘File::open‘, which returns a ‘Result<File, io::Error>‘ type. We use the ‘?‘ operator to propagate any errors from ‘File::open‘ up to the caller. If the file is opened successfully, we create a ‘BufReader‘ from the file and use its ‘lines‘ method to get an iterator over all lines in the file.
We then use ‘map‘ to convert the ‘Result<io::Result<String>, io::Error>‘ iterator into an iterator over ‘String‘s. We use ‘unwrap‘ to panick if there is an error on any of the lines. Finally, we collect the iterator into a vector of strings and return it as a successful result.
In the ‘main‘ function, we call ‘read_file_lines‘ with the file path and use the ‘?‘ operator again to propagate any errors up to the caller. If the function returns successfully, we print each line to the console.
If an error occurs during the execution of ‘read_file_lines‘, it will be returned as an ‘io::Error‘ type and propagated up to the caller of ‘main‘.