RsRust

Rust: Error handling – code examples

Contents

Handling a Result

Error handling#result#match#parse#errorCompare in all languages
Use case: Guarding user input or file access without crashing the program.
fn main() {
    match "abc".parse::<i32>() {
        Ok(n) => println!("Number: {n}"),
        Err(e) => println!("Invalid: {e}"),
    }
    let ergebnis: Result<i32, String> = Err("broken".to_string());
    println!("{}", ergebnis.unwrap_or(0));
}

Instead of try/except there is Result<T, E>. Cleanup (like finally) is handled automatically by the Drop trait at the end of the scope.

Using Option safely

Error handling#option#some#none
Use case: Modeling values that may be missing (search, configuration, first element) without null crashes.
fn erstes_wort(text: &str) -> Option<&str> {
    text.split_whitespace().next()
}

fn main() {
    println!("{:?}", erstes_wort("Hello World"));   // Some("Hello")
    println!("{:?}", erstes_wort("   "));          // None
    let name = erstes_wort("Ada Lovelace").map(|w| w.to_uppercase());
    println!("{}", name.unwrap_or_default());      // ADA
}

Option forces you to handle the “no value” case. map only transforms an existing Some, and unwrap_or_default otherwise returns the default value (an empty string).

Custom error type with From and ?

Error handling#error#from#question-mark
Use case: Passing several kinds of errors (file, parsing) on uniformly within one function.
use std::{fs, io, num::ParseIntError};

#[derive(Debug)]
enum AppFehler {
    Io(io::Error),
    Parse(ParseIntError),
}
impl From<io::Error> for AppFehler {
    fn from(e: io::Error) -> Self { AppFehler::Io(e) }
}
impl From<ParseIntError> for AppFehler {
    fn from(e: ParseIntError) -> Self { AppFehler::Parse(e) }
}

fn lies_zahl(pfad: &str) -> Result<i32, AppFehler> {
    let text = fs::read_to_string(pfad)?;
    Ok(text.trim().parse()?)
}

fn main() {
    println!("{:?}", lies_zahl("zahl.txt"));
}

? automatically converts errors into AppFehler via From. In libraries, the thiserror crate saves you this boilerplate.