Python Error Handling with Result<T, E> & the ? Operator
Rust separates errors into unrecoverable panics (panic!) and recoverable errors represented by Result<T, E> with variants Ok(T) and Err(E). The ? operator propagates errors up the call stack cleanly without nested match blocks.
"Result<T, E> is like a certified courier package: you open it and either find the ordered merchandise (Ok) or a return receipt with the reason for failure (Err). The ? operator says: "If this package has an error, hand it immediately to my manager and exit.""
Deep Dive: How It Works
The Result<T, E> Enum: enum Result<T, E> { Ok(T), Err(E) }.
The ? Operator: If Result is Ok(v), unwraps v. If Result is Err(e), returns Err(e) from the enclosing function immediately.
expect() vs unwrap(): expect("custom msg") provides a descriptive crash message if the Result was Err.
Syntax Blueprint
fn parse_num(s: &str) -> Result<i32, ParseIntError> { let n = s.parse::<i32>()?; Ok(n) }The ? operator replaces verbose match blocks for error propagation.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using ? in a function that does not return Result.Why it happens: The ? operator returns early with Err(e), so the enclosing function signature must return Result.
How to fix: Ensure functions using ? return Result<T, E> or Option<T>.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Safe division with Result
Write fn divide(a: i32, b: i32) -> Result<i32, &'static str> { if b == 0 { Err("Cannot divide by zero") } else { Ok(a / b) } }
In main(), match divide(100, 4) and print "Division Result: 25".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.