Error Handling (Rust)

Rust handles errors without exceptions. Recoverable failures use the Result<T, E> type and the ? operator; unrecoverable bugs use panic!. The compiler forces you to deal with the possibility of failure.

Rust

Rust splits errors into two categories. Recoverable errors (a file is missing, input won't parse) are returned as Result<T, E>; the caller must handle Ok and Err. Unrecoverable errors (broken invariants, bugs) trigger panic!, which ends the thread.

The ergonomic core is the ? operator, which propagates an Err up the call stack so you can chain fallible operations cleanly. Libraries often define custom error enums implementing the std::error::Error trait, and crates like thiserror and anyhow reduce the boilerplate of defining and combining errors.

Because failure is encoded in the type system rather than thrown invisibly, you can't accidentally ignore an error the way an unchecked exception can slip by. This makes Rust error handling explicit, local, and hard to get silently wrong.

Syntax

fn read_count(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n = s.trim().parse()?;
    Ok(n)
}

Examples

Rust

fn half(s: &str) -> Result<i32, std::num::ParseIntError> {
    let n: i32 = s.parse()?;
    Ok(n / 2)
}

fn main() {
    match half("10") {
        Ok(v) => println!("ok {}", v),
        Err(_) => println!("bad input"),
    }
}

Output:

ok 5

Learn it in a lesson

See also

Back to the Dictionary