RsRust
IntermediateLesson 9 of 16

Error Handling with Result & ? – Rust

Recoverable errors, the ? operator, and custom error types.

Rust has no exceptions. Errors that can occur are part of the return type: Result<T, E> is either Ok(T) or Err(E). Unrecoverable programming errors trigger a panic!.

use std::num::ParseIntError;

fn parse_und_verdopple(s: &str) -> Result<i32, ParseIntError> {
    let n: i32 = s.trim().parse()?;   // ? returns immediately on Err
    Ok(n * 2)
}

fn main() {
    match parse_und_verdopple("21") {
        Ok(v) => println!("{v}"),                     // 42
        Err(e) => println!("Error: {e}"),
    }
    println!("{:?}", parse_und_verdopple("abc"));     // Err(ParseIntError { kind: InvalidDigit })
}

The ? operator unwraps the value on Ok and does an early return on Err, automatically converting the error into the function's return error type via From. This replaces pages of error checks.

use std::fmt;

#[derive(Debug)]
enum KontoFehler {
    ZuWenig { saldo: u32, betrag: u32 },
    Gesperrt,
}

impl fmt::Display for KontoFehler {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            KontoFehler::ZuWenig { saldo, betrag } => {
                write!(f, "Balance {saldo} is not enough for {betrag}")
            }
            KontoFehler::Gesperrt => write!(f, "Account blocked"),
        }
    }
}

impl std::error::Error for KontoFehler {}

fn abheben(saldo: u32, betrag: u32) -> Result<u32, KontoFehler> {
    if betrag > saldo {
        Err(KontoFehler::ZuWenig { saldo, betrag })
    } else {
        Ok(saldo - betrag)
    }
}

fn main() {
    println!("{:?}", abheben(100, 30));      // Ok(70)
    if let Err(e) = abheben(50, 100) {
        println!("Error: {e}");
    }
}

For applications, Box<dyn Error> is a handy general-purpose error type, and even main may return a Result. Libraries, on the other hand, usually define their own error enums (often with the thiserror crate), while applications like to use anyhow.

use std::error::Error;
use std::fs;

fn main() -> Result<(), Box<dyn Error>> {
    let text = fs::read_to_string("zahl.txt")?;     // io::Error
    let n: i32 = text.trim().parse()?;              // ParseIntError
    println!("{}", n + 1);
    Ok(())
}
TipUseful: ok_or / ok_or_else (Option -> Result), map_err (convert the error), unwrap_or, unwrap_or_else, and_then. With .ok() you discard the error and get an Option.
Warning? only works in functions that themselves return Result or Option. In a main() without a return type you get a compiler error.