Sub topic 1
Rust Error Handling with the Question Mark Operator
Prerequisites
Assume you know basic Rust functions, enums, match, ownership, borrowing, and traits. You should also be able to build and run a Cargo project.
Result and Option: errors as values
Rust represents recoverable failure with Result<T, E>. It is an enum with two cases:
Ok(value)means the operation succeeded.Err(error)means it failed.
Option<T> is also an enum. Some(value) contains a value, while None represents an absent value. Use Result when you need to explain failure. Use Option when absence is expected and no error details are needed.
| Type | Success case | Failure or absence |
|---|---|---|
| `Result<T, E>` | `Ok(T)` | `Err(E)` |
| `Option<T>` | `Some(T)` | `None` |
flowchart TD
A[Operation] --> B{Result or Option}
B --> C[Ok or Some: continue]
B --> D[Err or None: handle or return]`unwrap`, `expect`, and panics
unwrap() extracts a success value but panics when it sees Err or None. expect("message") does the same and adds context. A panic stops normal recovery, so avoid these methods for expected failures such as missing files or invalid user input.
They can be reasonable when a failure indicates a programming bug, when a test needs a quick assertion, or when an invariant has already been proved.
Handling errors by hand
Use match when each outcome needs different logic. Combinators such as map, map_err, ok_or, and and_then transform values without writing every branch manually.
use std::num::ParseIntError;
fn parse_port(text: &str) -> Result<u16, ParseIntError> {
text.trim()
.parse::<u16>()
.map_err(|error| error)
}
fn main() {
match parse_port("8080") {
Ok(port) => println!("port = {port}"),
Err(error) => eprintln!("invalid port: {error}"),
}
}Here, map_err could transform the parse error into a custom error. In this example, it returns the same error unchanged.
Propagating errors with `?`
The ? operator handles the success path and returns an error early:
use std::fs;
use std::io;
fn read_count(path: &str) -> Result<u32, io::Error> {
let text = fs::read_to_string(path)?;
let count = text.trim().parse::<u32>()
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
Ok(count)
}The function must return a compatible Result. If reading or parsing fails, ? stops the function and returns the error to its caller. Otherwise, it produces the successful value.
Exercise
Why does read_count need a Result return type?
Show answer
Because ? may return an error early, so the function must provide a compatible place to return that error.