liveBook · Manning

Exception

As explained in Idiomatic Rust

Error handling is the practice of detecting, representing, propagating, and responding to failures during program execution.

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

How Idiomatic Rust covers it

How deep it goes
Explains custom error types, Result/Option propagation with ?, conversion through From, and explicit handling; treats implementing std::error::Error as optional.
Examples
Demonstrates reading a file’s nth line, handling I/O and invalid-line errors, and testing failures; also cautions against casual unwrap().
What you can do after
Apply it by defining error types, returning Result, propagating with ?, and explicitly handling cases that need action.
How it connects
Connects Result and Option to pattern matching, the ? operator, From conversions, and std::error::Error.

Also explained in

Compare how 25 books explain exception →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.