Rust Tutorial: Error Handling
Result<T,E> for recoverable errors, the ? operator, and when to use panic vs Result.
No exceptions
Rust has no exceptions. Errors are values — either `panic!` for unrecoverable bugs, or `Result<T, E>` for expected failures.
This design forces you to think about errors at every step. The `?` operator makes it painless.
What you'll learn in this Rust error handling tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Result type — `Result<T, E>` is either `Ok(value)` or `Err(error)`. Functions return it to signal possible failure.
- match on Result — Handle both variants explicitly with match.
- The ? operator — `?` after a Result either unwraps Ok or returns the Err to the caller.
- unwrap and expect — `unwrap()` panics on Err. `expect(msg)` panics with a custom message.
- map and and_then on Result — `map` transforms Ok. `and_then` chains fallible operations.
- unwrap_or and unwrap_or_else — Provide a fallback value instead of panicking.
- Collecting Results — When mapping over an iterator and each operation returns Result, collect into `Result<Vec<T>, E>` to fail fast.
- panic! for bugs — `panic!` is for unrecoverable bugs — index out of bounds, contract violations.
Rust Error Handling concepts covered
- No exceptions