Advanced 18 min readModule: Module 8: Error Handling with Result<T, E>
Result<T, E> & The '?' Error Propagation Operator
Handle recoverable errors gracefully with Result and propagate errors with the '?' operator.
What You Will Learn in This Lesson
- The Result<T, E> enum (Ok(T) vs Err(E))
- Propagating errors effortlessly with the '?' operator
- Mapping and chaining errors with .map_err() and thiserror/anyhow
Introduction & Core Concept
Rust distinguishes between recoverable errors (using Result<T, E>) and unrecoverable errors (which call the panic! macro).
WHY DOES THIS MATTER IN THE REAL WORLD?
The '?' operator returns the Err early from the current function if an error occurs, eliminating 5 lines of boilerplate per call.
Error Propagation with '?' Operator
rustrust
1234567891011fn parse_port(port_str: &str) -> Result<u16, std::num::ParseIntError> {let port: u16 = port_str.parse()?;Ok(port)}fn main() {match parse_port("8080") {Ok(port) => println!("Server listening on port: {}", port),Err(e) => println!("Invalid port: {}", e),}}
Line-by-Line Technical Breakdown
1Unwrap (.unwrap()) should only be used in quick prototypes or unit tests.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[RUST]
RUST SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Always return Result<T, E> from functions that perform I/O or parsing.
Lesson Summary & Core Takeaways
- Result and the '?' operator make robust error handling ergonomic.