Module 08 Exercises — Option, Result & Error Handling
How to use this page
Attempt every exercise in a real Cargo project before opening a solution — a solution you have not fought for teaches almost nothing. Tick the boxes as you go; progress is saved in this browser.
Before you start, be able to explain:
- why
Optionprevents a class of bug thatnullcannot; - exactly what
?expands to, in the two-branch form; - when a panic is legitimate and when it is you avoiding a decision.
A good self-test while working through these: every time you type .unwrap(), stop and ask what you would write instead if this were going into production. Sometimes the honest answer is expect with a real sentence — that is a fine outcome.
Part A — Warm-Up Drills
Short reps on the mechanics. Do them until the syntax stops costing you any thought.
🟢 Exercise 8.1 — Option combinators
Rewrite without match or if let:
fn double_first(v: &[i32]) -> Option<i32> {
match v.first() {
Some(x) => Some(x * 2),
None => None,
}
}Solution
fn double_first(v: &[i32]) -> Option<i32> {
v.first().map(|x| x * 2)
}🟢 Exercise 8.2 — Safe division
Write fn divide(a: f64, b: f64) -> Result<f64, String> returning an error on zero.
Then chain three divisions with ? inside a helper returning Result.
Solution
fn divide(a: f64, b: f64) -> Result<f64, String> {
if b == 0.0 { Err("division by zero".to_string()) } else { Ok(a / b) }
}
fn compute() -> Result<f64, String> {
let x = divide(100.0, 5.0)?;
let y = divide(x, 2.0)?;
let z = divide(y, 0.0)?; // short-circuits here
Ok(z)
}
fn main() { println!("{:?}", compute()); } // Err("division by zero")Part B — Core Exercises
The real practice. Attempt each one fully — compiler errors included — before opening a solution.
🟡 Exercise 8.3 — Parse a config line
Write fn parse_kv(line: &str) -> Result<(String, i32), String> that parses "key=42".
Errors: missing =, empty key, non-numeric value — each with a distinct message. Use ?
and ok_or.
Solution
fn parse_kv(line: &str) -> Result<(String, i32), String> {
let (key, value) = line.split_once('=').ok_or("missing '='")?;
let key = key.trim();
if key.is_empty() { return Err("empty key".to_string()); }
let value: i32 = value.trim().parse().map_err(|e| format!("bad value: {e}"))?;
Ok((key.to_string(), value))
}
fn main() {
println!("{:?}", parse_kv("timeout = 30")); // Ok(("timeout", 30))
println!("{:?}", parse_kv("broken")); // Err("missing '='")
println!("{:?}", parse_kv("= 5")); // Err("empty key")
println!("{:?}", parse_kv("x = abc")); // Err("bad value: ...")
}🟡 Exercise 8.4 — Custom error with From
Define enum AppError { Io(std::io::Error), Parse(std::num::ParseIntError) } with
Display, Error, and both From impls. Then write
fn sum_file(path: &str) -> Result<i64, AppError> that reads a file of one integer per
line and sums them — using only ?, no match.
Solution
use std::fmt;
#[derive(Debug)]
enum AppError { Io(std::io::Error), Parse(std::num::ParseIntError) }
impl fmt::Display for AppError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
AppError::Io(e) => write!(f, "io error: {e}"),
AppError::Parse(e) => write!(f, "parse error: {e}"),
}
}
}
impl std::error::Error for AppError {}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self { AppError::Io(e) }
}
impl From<std::num::ParseIntError> for AppError {
fn from(e: std::num::ParseIntError) -> Self { AppError::Parse(e) }
}
fn sum_file(path: &str) -> Result<i64, AppError> {
let text = std::fs::read_to_string(path)?; // io::Error -> AppError
let mut total = 0i64;
for line in text.lines() {
if line.trim().is_empty() { continue; }
total += line.trim().parse::<i64>()?; // ParseIntError -> AppError
}
Ok(total)
}
fn main() {
std::fs::write("nums.txt", "1\n2\n3\n").unwrap();
println!("{:?}", sum_file("nums.txt")); // Ok(6)
println!("{:?}", sum_file("missing.txt")); // Err(Io(...))
}Two different error types flow through the same ? because of the two From impls.
That's the mechanism to internalize.
Part C — Challenges
Longer builds. Expect to fight the borrow checker here; that fight is the lesson.
🔴 Exercise 8.5 — Collecting results
Given let inputs = vec!["1", "2", "x", "4"];:
- Produce
Result<Vec<i32>, ParseIntError>that fails on the first bad input. - Produce
(Vec<i32>, Vec<String>)of successes and error messages, keeping everything. - Produce
Vec<i32>of only the successes.
Solution
use std::num::ParseIntError;
fn main() {
let inputs = vec!["1", "2", "x", "4"];
// 1. all-or-nothing — collect into Result<Vec<_>, _> inverts the containers
let all: Result<Vec<i32>, ParseIntError> =
inputs.iter().map(|s| s.parse::<i32>()).collect();
println!("{all:?}"); // Err(ParseIntError { .. })
// 2. partition
let (oks, errs): (Vec<_>, Vec<_>) = inputs
.iter()
.map(|s| s.parse::<i32>())
.partition(|r| r.is_ok());
let oks: Vec<i32> = oks.into_iter().map(Result::unwrap).collect();
let errs: Vec<String> = errs.into_iter().map(|e| e.unwrap_err().to_string()).collect();
println!("{oks:?} {errs:?}"); // [1, 2, 4] ["invalid digit..."]
// 3. keep successes only
let good: Vec<i32> = inputs.iter().filter_map(|s| s.parse().ok()).collect();
println!("{good:?}"); // [1, 2, 4]
}collect::<Result<Vec<_>, _>>() is one of the most useful tricks in the language — it
turns an iterator of Results into a Result of a collection, short-circuiting on the
first error.
Self-check
- What does
?do onErr, exactly? - Which trait makes
?convert error types automatically? - Why is
Resultmarked#[must_use]? thiserrororanyhow— which goes in a library?- Give two situations where
unwrap()is acceptable.
Answers
- Returns early from the enclosing function with
Err(From::from(e)). From.- So an ignored failure produces a compiler warning rather than silently vanishing.
thiserror— it exposes a matchable error type.anyhowis for binaries.- Tests, and prototype/example code (plus cases where
None/Erris a genuine invariant violation — but thereexpectwith a reason is better).
