Skip to content

Error Handling

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());
## Intuition

Rust uses Result<T, E> instead of exceptions. The ? operator propagates errors up the call stack concisely. Optionhandles nullable values without null pointer exceptions. This explicit error handling makes failure paths visible in function signatures, forcing callers to handle errors. The type system ensures you cannot accidentally ignore a Result, and the compiler guides you toward proper error recovery patterns.

  • [[rust/02-ownership-borrowing/ownership]] - Ownership of error values
  • [[rust/03-structs-enums/structs-and-enums]] - Custom error types with enums
  • [[rust/05-traits-generics/traits-and-generics]] - From trait for error conversion
  • [[rust/04-error-handling/error-handling-patterns]] - Advanced error handling patterns