Skip to content
RustLearn

Module 08 — Option, Result & Error Handling

Goal

No null, no exceptions. Absence and failure are ordinary values the type system forces you to handle — plus ?, custom error types and error conversion.

Start here — what this module is really about

Rust has no null, and it has no exceptions. Both of those absences are deliberate, and this module is what replaces them.

Instead of null, there is Option<T>. When a value might be missing, its type says so:

rust
enum Option<T> {
    Some(T),   // there is a value, and here it is
    None,      // there is not
}

The difference from null is not cosmetic. A null looks exactly like a real value right up to the moment you use it, which is why the null dereference is the most common crash in software. An Option is a different type: you cannot accidentally treat Option<String> as a String, because the compiler will not let you. You have to open it, and opening it means deciding what happens when it is empty.

Instead of exceptions, there is Result<T, E>. When an operation can fail, its type says so:

rust
enum Result<T, E> {
    Ok(T),     // it worked, here is the value
    Err(E),    // it failed, here is why
}

An exception travels invisibly: you cannot tell from a function's signature whether it might throw, and the handler may be several layers away, or absent. A Result is an ordinary value returned to the caller, and the compiler warns if you ignore it. Failure stops being a surprise and becomes part of the contract.

Both are just enums — the enums from module 07, in the standard library. Everything you learned about match applies directly. What this module adds is the ergonomics: the ? operator that makes propagating failure a single character, and how to build your own error types so a library reports failures in its own vocabulary.

The one sentence to remember: absence and failure are ordinary values with ordinary types, so the compiler can make sure you deal with them.

Learning objectives

  • Use Option<T> to eliminate null
  • Use Result<T, E> to eliminate exceptions
  • Apply the combinator toolkit (map, and_then, unwrap_or, ok_or, ...)
  • Propagate errors with ? and understand its conversion behaviour
  • Build custom error types, implement std::error::Error, and use thiserror/anyhow
  • Know when panicking is correct

8.1 Option<T>: null, done right

rust
enum Option<T> {
    None,
    Some(T),
}

That's the entire definition — it's in the prelude, so Some and None need no import.

The crucial property: Option<T> and T are different types. You cannot use an Option<i32> where an i32 is expected, so you cannot forget to handle absence.

rust
let x: i8 = 5;
let y: Option<i8> = Some(5);
// let sum = x + y;    // ❌ E0277: cannot add `Option<i8>` to `i8`
let sum = x + y.unwrap_or(0);   // ✅ absence handled explicitly

Tony Hoare called null his "billion-dollar mistake". Rust's answer isn't to remove absence — it's to make absence visible in the type and impossible to ignore.

Extracting the value

rust
let v = Some(5);

// 1. match — always available, most explicit
match v {
    Some(n) => println!("{n}"),
    None => println!("nothing"),
}

// 2. if let / let else
if let Some(n) = v { println!("{n}"); }
let Some(n) = v else { return };

// 3. combinators — usually the best
v.unwrap_or(0);                 // default value
v.unwrap_or_default();          // T::default()
v.unwrap_or_else(|| expensive());   // lazily computed default
v.map(|n| n * 2);               // Option<i32> -> Option<i32>
v.filter(|n| *n > 3);           // keep only if predicate holds
v.and_then(|n| checked(n));     // flatMap: returns Option
v.ok_or("was none");            // Option<T> -> Result<T, E>
v.is_some(); v.is_none();
v.take();                       // (on &mut) replace with None, return old
v.as_ref();                     // Option<T> -> Option<&T>

// 4. unwrap / expect — panics on None. Use only when None is a BUG.
v.unwrap();
v.expect("config must be loaded before use");

Style rule

Never ship .unwrap() in library or production code paths that can fail on user input. .expect("reason") is acceptable when the None case would mean your program's invariants are already broken — and the message should explain why you believe it can't happen.

Chaining

rust
fn first_char_upper(s: &str) -> Option<char> {
    s.chars().next().map(|c| c.to_ascii_uppercase())
}

let config: Option<String> = std::env::var("PORT").ok();
let port: u16 = config
    .and_then(|s| s.parse().ok())
    .filter(|p| *p > 1024)
    .unwrap_or(8080);

Each step short-circuits on None, so there is no nesting and no null check.


Getting a value out of an Option, five ways

You have an Option<String> and you want the String. Here is the full menu, worst to best:

rust
let name: Option<String> = find_user(42);

// 1. .unwrap() — give me the value, and crash the program if it is None.
let n = name.unwrap();

// 2. .expect("msg") — same, but the crash message explains what you assumed.
let n = name.expect("user 42 must exist: seeded in setup");

// 3. .unwrap_or(default) — use this fallback if it is None.
let n = name.unwrap_or(String::from("anonymous"));

// 4. if let — do something only when there is a value.
if let Some(n) = name {
    println!("hello {n}");
}

// 5. match — handle both cases explicitly.
match name {
    Some(n) => println!("hello {n}"),
    None => println!("nobody home"),
}

How to choose, in practice:

  • unwrap() in real code is a promise you are making to the compiler that you cannot keep. It is fine in a quick experiment or a test. In anything long-lived, prefer expect with a message stating why you believe it cannot be None — when it panics anyway, that sentence is what tells you which assumption broke.
  • unwrap_or and friends (unwrap_or_else, unwrap_or_default) are usually the right answer when a sensible fallback exists.
  • if let when only one case is interesting.
  • match when both cases need real work.

The common thread: none of these let you forget that the value might be missing. That is the whole point.

Analogy — the empty box is still a box

null is an empty space on the shelf that looks exactly like a full one until you reach for it. Option<T> is a labelled box: it may be empty, but it is unmistakably a box, and you cannot get at the contents without first opening the lid and dealing with the possibility that there is nothing inside. Every null-pointer crash you have ever debugged was the shelf; this is the box.

8.2 Result<T, E>: errors as values

rust
enum Result<T, E> {
    Ok(T),
    Err(E),
}

Rust has no exceptions. A function that can fail says so in its return type:

rust
use std::fs::File;

fn main() {
    let f = File::open("hello.txt");
    match f {
        Ok(file) => println!("opened {file:?}"),
        Err(e) => println!("failed: {e}"),
    }
}

Because Result is #[must_use], ignoring one produces a warning — you cannot silently drop a failure.

The combinator set

rust
let r: Result<i32, String> = Ok(2);

r.unwrap_or(0);
r.unwrap_or_else(|e| e.len() as i32);
r.map(|v| v * 2);              // transform the Ok value
r.map_err(|e| format!("ctx: {e}"));  // transform the Err value
r.and_then(|v| checked(v));    // chain another fallible step
r.ok();                        // Result<T, E> -> Option<T>, discards the error
r.is_ok(); r.is_err();
r.expect("must succeed");

Matching on the error kind

rust
use std::fs::File;
use std::io::ErrorKind;

let f = match File::open("hello.txt") {
    Ok(file) => file,
    Err(e) => match e.kind() {
        ErrorKind::NotFound => File::create("hello.txt").expect("could not create"),
        other => panic!("problem opening file: {other:?}"),
    },
};

Analogy — the delivery receipt

An exception is a courier who, on failing to deliver, vanishes and sets off an alarm somewhere else in the building — possibly several floors up, possibly nowhere. A Result is a courier who always comes back to your desk with a receipt reading either delivered or failed, here is why. The failure is ordinary paperwork you handle where you stand, not an emergency thrown over the wall.

8.3 The ? operator

? is the whole reason Rust's error handling stays readable.

rust
use std::fs::File;
use std::io::{self, Read};

// Without ?
fn read_username_verbose() -> Result<String, io::Error> {
    let f = File::open("hello.txt");
    let mut f = match f {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut s = String::new();
    match f.read_to_string(&mut s) {
        Ok(_) => Ok(s),
        Err(e) => Err(e),
    }
}

// With ?
fn read_username() -> Result<String, io::Error> {
    let mut s = String::new();
    File::open("hello.txt")?.read_to_string(&mut s)?;
    Ok(s)
}

// Or just
fn read_username_short() -> Result<String, io::Error> {
    std::fs::read_to_string("hello.txt")
}

expr? means: if Ok(v), evaluate to v; if Err(e), return early with Err(From::from(e)).

That From::from is important: ? automatically converts the error type, so a function returning Result<T, MyError> can use ? on any error that implements From<ThatError> for MyError.

Rules:

  • ? only works in functions returning Result, Option, or another Try type.
  • In a function returning Option, ? returns early on None.
  • main may return Result<(), Box<dyn Error>>, which lets you use ? at the top level:
rust
use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {
    let content = std::fs::read_to_string("config.toml")?;
    println!("{content}");
    Ok(())
}

A non-zero exit code and a Debug-printed error are produced automatically on Err.


What ? actually expands to

The ? operator is the reason Rust error handling stays readable. Here is the same function written both ways:

rust
// Without ?
fn read_config() -> Result<String, io::Error> {
    let mut file = match File::open("config.toml") {
        Ok(f) => f,
        Err(e) => return Err(e),          // failed — hand it back to the caller
    };
    let mut contents = String::new();
    match file.read_to_string(&mut contents) {
        Ok(_) => Ok(contents),
        Err(e) => Err(e),
    }
}

// With ?
fn read_config() -> Result<String, io::Error> {
    let mut file = File::open("config.toml")?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)?;
    Ok(contents)
}

? means exactly this: if this is Ok, unwrap it and carry on; if it is Err, return that error from this function immediately.

Three consequences worth knowing:

  1. ? only works in a function that returns Result (or Option). It returns from your function, so your function must have somewhere to return an error to. The error the ? operator can only be used in a function that returns Result means exactly that.
  2. It is not silent swallowing. The failure keeps travelling up until it reaches code whose job is to decide — usually main, or a request handler.
  3. It converts error types on the way, using the From trait. That is how a function returning Box<dyn Error> can ? on both an io::Error and a ParseIntError — §8.4 shows how to set this up for your own error type.

Analogy — pass it up the chain

? is the office rule that says: if this step failed and it is not your call to make, hand the memo straight up to your manager, unchanged, and stop. It reads as one character because that is how often you need it — and it is not silent swallowing: the failure keeps travelling until it reaches someone whose job it is to decide.

8.4 Custom error types

Step 1: a plain enum

rust
use std::fmt;

#[derive(Debug)]
enum ConfigError {
    NotFound(String),
    Invalid { field: String, reason: String },
    Io(std::io::Error),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ConfigError::NotFound(p) => write!(f, "config file not found: {p}"),
            ConfigError::Invalid { field, reason } => write!(f, "invalid `{field}`: {reason}"),
            ConfigError::Io(e) => write!(f, "io error: {e}"),
        }
    }
}

impl std::error::Error for ConfigError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ConfigError::Io(e) => Some(e),
            _ => None,
        }
    }
}

// This impl is what makes `?` work on io::Error inside functions returning ConfigError
impl From<std::io::Error> for ConfigError {
    fn from(e: std::io::Error) -> Self { ConfigError::Io(e) }
}

Now:

rust
fn load(path: &str) -> Result<String, ConfigError> {
    let text = std::fs::read_to_string(path)?;   // io::Error -> ConfigError via From
    if text.trim().is_empty() {
        return Err(ConfigError::Invalid { field: "root".into(), reason: "empty".into() });
    }
    Ok(text)
}

The three traits a good error type implements: Debug (derive), Display (by hand), and std::error::Error (usually empty except source).

Step 2: let thiserror write it

toml
[dependencies]
thiserror = "1"
rust
use thiserror::Error;

#[derive(Debug, Error)]
enum ConfigError {
    #[error("config file not found: {0}")]
    NotFound(String),
    #[error("invalid `{field}`: {reason}")]
    Invalid { field: String, reason: String },
    #[error("io error")]
    Io(#[from] std::io::Error),      // generates the From impl AND source()
}

Identical behaviour, four lines instead of forty.

Step 3: anyhow for applications

Libraries should expose precise error enums so callers can match on them. Applications usually just want to report and exit:

toml
anyhow = "1"
rust
use anyhow::{Context, Result, bail};

fn load(path: &str) -> Result<String> {
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read config at {path}"))?;
    if text.is_empty() {
        bail!("config at {path} is empty");
    }
    Ok(text)
}

anyhow::Error boxes any error and accumulates a context chain, printed as:

Error: failed to read config at /etc/app.toml

Caused by:
    No such file or directory (os error 2)

Rule

thiserror in libraries, anyhow in binaries. Never anyhow in a public library API — it robs callers of the ability to handle specific cases.

8.5 When to panic

Panic is for bugs, not for expected failure.

SituationUse
File might not existResult
User typed a non-numberResult
Network request failedResult
Index out of bounds in your own logicpanic (via indexing)
An invariant your code guarantees was violatedpanic! / unreachable!
Prototype/example codeunwrap() is fine
Testsunwrap()/expect() is fine and idiomatic

Useful panic macros: panic!, unreachable!, todo!, unimplemented!, assert!, assert_eq!, debug_assert!.

Panics unwind the stack by default (running destructors). You can configure abort:

toml
[profile.release]
panic = "abort"

Panic or Result? A decision you can make mechanically

Ask one question: could a correct program, given valid inputs, hit this?

  • Yes → return a Result. A file the user named does not exist. Their input was not a number. The network was down. None of that is a bug in your code; it is the world being the world, and the caller deserves the chance to respond.
  • No → panic! is legitimate. An index that your own invariants guarantee is in range. A configuration constant you compiled in. A case in your own state machine that cannot occur unless your logic is wrong.

Two refinements that matter in practice:

  • Libraries almost never panic on the caller's behalf. Your crate cannot know whether a failure is fatal to their program. Return the error and let them decide.
  • Applications may panic at the edges. Failing to parse your own config file at start-up is fine to treat as fatal — there is nothing sensible to continue with.

And note what panic! actually does: it unwinds the stack, running Drop for everything on the way, then ends the thread. It is not an exception, because you are not meant to catch it and carry on.

Analogy — the fire alarm is not the to-do list

A missing config file at start-up is a fire alarm: the programme cannot sensibly continue, so panic! and stop the building. A malformed line in a user's upload is a to-do item: return a Result and let the caller decide whether to skip it, report it, or give up. Libraries almost never pull the alarm on someone else's behalf.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
Option<T>A value that is either Some(value) or None. Replaces null.
Result<T, E>An outcome that is either Ok(value) or Err(error). Replaces exceptions.
unwrap()Take the value, panicking if there is not one. Convenient, unsafe for real code.
expect("...")Same, with a message explaining the assumption you made.
?Unwrap on success, or return the error from the current function.
propagatePass an error up to your caller rather than handling it here.
panic!Abort the current thread with a message. For bugs, not for expected failures.
unwindingThe cleanup that runs on the way out of a panic, dropping values properly.
FromThe trait that converts one type into another — what lets ? change error types.
Box<dyn Error>A catch-all error type: "some error, details decided at runtime".
combinatorMethods like map, and_then, ok_or that transform an Option/Result without unwrapping it.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0277]: the ? operator can only be used in a function that returns ResultYou used ? in a function returning something else.Change the signature to -> Result<T, E>, or handle the error here with match.
error[E0308]: expected String, found Option<String>You used the container where the value was expected.Open it first: match, if let, or unwrap_or.
called Option::unwrap() on a None value (at runtime)Your unwrap assumption was wrong.Replace with expect explaining the assumption, or handle None properly.
warning: unused Result that must be usedYou called something fallible and ignored the outcome.Handle it, propagate it with ?, or say you meant it with let _ = ....
error[E0277]: ? couldn't convert the errorThe error type you got cannot become the error type you return.Implement From for your error type (§8.4), or return Box<dyn Error>.

Now make it stick: work through the drills for this module, then carry on to Module 09 — Collections & Strings.