Rust error handling centers on Result: define errors as structs or enums, then choose whether to handle each case or return it to the caller. section 4.5
Choose an approach that matches the failure:
- Represent useful error details in a custom type; wrap standard-library errors such as std::io::Error when needed. section 4.5
- Match on results or use other control flow when a failure needs an explicit response. section 4.5
- Use ? to return early on Err or None and pass failures up the call chain; conversions may require implementing From. section 4.5
- Avoid casual unwrap(): it can hide failure paths. When failure is expected to be impossible, prefer expect() with a useful message. section 10.3
Listing 4.11 Reading the nth line from a file
use std::path::Path;
#[derive(Debug)]
pub enum Error { #1
Io(std::io::Error), #2
BadLineArgument(usize), #3
}
impl From<std::io::Error> for Error { #4
fn from(error: std::io::Error) -> Self {
Self::Io(error)
}
}
fn read_nth_line(path: &Path, n: usize) -> Result<String, Error> {
use std::fs::File;
use std::io::{BufRead, BufReader};
let file = File::open(path)?; #5
let mut reader_lines = BufReader::new(file).lines(); #6
reader_lines
.nth(n - 1) #7
.map(|result| result.map_err(|err| err.into())) #8
.unwrap_or_else(|| Err(Error::BadLineArgument(n))) #9
}
A file-reading function combines an error enum, From conversion, and ? propagation; it reports a missing line as a separate error. section 4.5
























