Skip to content

Error Handling | Rust - Wyatt's Notes

import Citations from ‘@components/Citations.astro’

Rust divides errors into two categories: unrecoverable (bugs) and recoverable (expected Failures).

Panics are for unrecoverable programming errors — the kind of bugs where the program cannot continue Correctly. When a panic occurs, the runtime unwinds the stack (by default), calling destructors for All live values, and then aborts the thread (or the process in panic = "abort" mode).

fn main() {
panic!("this is a deliberate crash");
}

Common panic sources:

  • unwrap() on None or Err
  • Array index out of bounds
  • Integer overflow in debug mode
  • assert!``assert_eq!``assert_ne! failures
  • Calling panic! directly
  • Division by zero

The default panic strategy is unwinding (destructors run). You can set panic = "abort" in Cargo.toml to terminate immediately without unwinding:

[profile.release]
panic = "abort"

Trade-offs:

  • Unwinding: Safe cleanup (destructors run, Drop::drop is called), larger binary size (unwind tables), slightly slower.
  • Abort: Smaller binary, faster, but no cleanup. File handles, network connections, and locks may not be released properly.

For embedded and no_std targets, panic = "abort" is often the only option.

You can catch panics in the current thread:

use std::panic;
fn may_panic() -> i32 {
panic!("crash");
}
let result = panic::catch_unwind(may_panic);
assert!(result.is_err());

Rust splits errors into two bins: bugs (panics) and expected failures (Results). Panics are for things that should never happen, like indexing out of bounds. Results are for things that might fail, like reading a file. The ? operator is the magic wand: it either unwraps the success value or propagates the error upward. Think of Result as a postal package that is either delivered (Ok) or returned to sender (Err). The type system forces you to acknowledge every possible failure, so forgotten error handling is impossible.

<Citations sources={[ {title=“The Rust Programming Language”, author=“Klabnik and Nichols”, year=“2024”, type=“book”, url=“https://doc.rust-lang.org/book/”}, {title=“Rust for Rustaceans”, author=“Gjengset”, year=“2021”, type=“book”}, ]} />