Error Handling Without Exceptions
local graph
Chapter 8 — Error Handling Without Exceptions
Section titled “Chapter 8 — Error Handling Without Exceptions”Errare humanum est. (To err is human.)
The Result<T, E> type appeared briefly in the previous chapter as an example of a generic enum with two type parameters. Its role in Rust extends far beyond being a teaching example. Result is the foundation of error handling in Rust, replacing the exception-based approach familiar to Java, C#, and C++ developers. Where those languages use try-catch blocks and stack unwinding, Rust treats errors as values that must be explicitly handled. This shift changes how code is structured, how errors propagate, and how failures are reasoned about.
Exception-based error handling has a fundamental problem: hidden control flow. A method that might throw an exception looks identical to one that cannot. The call user.save() might return normally, or it might jump to a catch block fifty frames up the stack, unwinding everything in between. Java’s checked exceptions attempted to make this visible, requiring methods to declare their exceptions, but the design proved unwieldy and fell out of favor. Modern Java code increasingly uses unchecked exceptions, returning to invisible failure modes. C# and C++ never attempted mandatory exception declarations, leaving error paths entirely implicit.
Rust makes error handling explicit through the type system. A function that can fail returns Result<T, E>, where T is the success type and E is the error type. A function returning Result<User, DatabaseError> communicates through its signature that database failures are possible. Callers must acknowledge this possibility; the code does not compile if they ignore it. The error case is not an exceptional path that might be forgotten. It is part of the function’s contract, visible in its type.
Result as the primary Error channel
The Result enum has two variants: Ok contains a success value, and Err contains an error value. This mirrors Option’s Some and None, but Result carries information about what went wrong rather than signaling absence:
enum Result<T, E> { Ok(T), Err(E),}A function reading a configuration file might return Result<Config, io::Error>. Success produces a Config value wrapped in Ok. Failure produces an io::Error wrapped in Err. The caller decides how to proceed:
fn load_config(path: &str) -> Result<Config, io::Error> { let contents = std::fs::read_to_string(path)?; let config = parse_config(&contents)?; Ok(config)}
fn main() { match load_config("settings.toml") { Ok(config) => println!("Loaded: {:?}", config), Err(e) => eprintln!("Failed to load config: {}", e), }}Pattern matching on Result forces acknowledgment of both cases. The compiler rejects code that handles only Ok without addressing Err.
This is not a convention or a lint warning. It is a property of the type system that cannot be circumvented.
Compare this to exception-based code where the happy path and error path diverge invisibly. A Java method loadConfig() returns Config, and whether it throws an exception is hidden from the call site. The Rust signature fn load_config(…) -> Result<Config, io::Error> makes the possibility of failure a first-class part of the API.
Methods on Result
Result provides methods for common operations, reducing the need for explicit pattern matching in simple cases. The unwrap method extracts the Ok value or panics if the Result is Err:
let config = load_config("settings.toml").unwrap();This is convenient for prototyping or situations where failure is truly unexpected, but it converts recoverable errors into crashes. Production code typically avoids unwrap except where correctness is guaranteed by prior checks or invariants.
The expect method works like unwrap but includes a custom panic message:
let config = load_config("settings.toml") .expect("Configuration file must exist");The message helps diagnose failures when reading logs or crash reports.
The unwrap_or method provides a default value when the Result is Err:
let config = load_config("settings.toml") .unwrap_or(Config::default());This is useful when a sensible default exists and failure is acceptable.
The map method transforms the Ok value without affecting Err:
let name: Result<String, io::Error> = load_config("settings.toml") .map(|config| config.name.clone());If the Result is Ok, the closure runs and the return value becomes the new Ok. If the Result is Err, the error passes through unchanged.
The map_err method does the opposite, transforming the error:
let result: Result<Config, String> = load_config("settings.toml") .map_err(|e| format!("Config error: {}", e));These methods enable functional composition without nested match expressions. They chain naturally, building pipelines that handle both success and failure paths.
The ? operator and propagation
Manual propagation of errors through match expressions becomes verbose in functions performing multiple fallible operations. Each operation requires matching on its Result, returning early on Err, and extracting the value on Ok before proceeding:
fn process_data(path: &str) -> Result<Summary, io::Error> { let contents = match std::fs::read_to_string(path) { Ok(s) => s, Err(e) => return Err(e), }; let data = match parse_data(&contents) { Ok(d) => d, Err(e) => return Err(e), }; let summary = match analyze(&data) { Ok(s) => s, Err(e) => return Err(e), }; Ok(summary)}This pattern appears constantly in error-handling code. The ? operator provides syntactic sugar for exactly this pattern:
fn process_data(path: &str) -> Result<Summary, io::Error> { let contents = std::fs::read_to_string(path)?; let data = parse_data(&contents)?; let summary = analyze(&data)?; Ok(summary)}The ? operator on a Result expression does the following: if the Result is Ok, it extracts and returns the inner value. If the Result is Err, it returns early from the enclosing function with that error. The two versions of process_data are equivalent, but the second is vastly more readable.
The ? operator can only be used in functions that return Result (or Option, with slightly different semantics). The compiler checks that the return type matches and that error types are compatible. This is not a general-purpose early return mechanism; it is specifically for propagating errors up the call stack.
Error type conversion
When a function performs operations that produce different error types, the ? operator requires that those errors convert into the function’s return error type. If read_to_string returns Result<String, io::Error> but the function returns Result<Summary, MyError>, the conversion must be possible.
The From trait enables this conversion. If MyError implements From<io::Error>, the ? operator automatically converts io::Error into MyError:
#[derive(Debug)]enum MyError { Io(io::Error), Parse(ParseError),}
impl From<io::Error> for MyError { fn from(error: io::Error) -> Self { MyError::Io(error) }}
impl From<ParseError> for MyError { fn from(error: ParseError) -> Self { MyError::Parse(error) }}With these implementations, a function returning Result<T, MyError> can use ? on operations returning either io::Error or ParseError. The conversion happens automatically, unifying different error sources into a single error type.
This pattern is so common that crates like thiserror provide derive macros to reduce the boilerplate. However, understanding the underlying mechanism is important. The ? operator is not magic; it relies on From implementations that can be inspected and customized.
Custom Error types
Applications and libraries benefit from defining their own error types rather than propagating standard library errors directly. Custom error types provide context specific to the domain, enable structured error handling by callers, and create a stable error API independent of implementation details.
An enum works well for errors with distinct variants:
#[derive(Debug)]pub enum ConfigError { FileNotFound(PathBuf), ParseError { line: usize, message: String }, InvalidValue { key: String, value: String },}Each variant carries information specific to that error kind. Pattern matching on ConfigError lets callers handle specific cases differently:
match load_config("settings.toml") { Ok(config) => use_config(config), Err(ConfigError::FileNotFound(path)) => { eprintln!("Config file not found: {}", path.display()); create_default_config()?; } Err(ConfigError::ParseError { line, message }) => { eprintln!("Parse error at line {}: {}", line, message); return Err(ConfigError::ParseError { line, message }); } Err(e) => return Err(e),}For errors that need to be displayed to users or logged, implementing
the std::fmt::Display trait is essential:
impl std::fmt::Display for ConfigError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ConfigError::FileNotFound(path) => { write!(f, "configuration file not found: {}", path.display()) } ConfigError::ParseError { line, message } => { write!(f, "parse error at line {}: {}", line, message) } ConfigError::InvalidValue { key, value } => { write!(f, "invalid value '{}' for key '{}'", value, key) } } }}The standard library provides the std::error::Error trait for error types. Implementing this trait enables integration with error handling utilities and the ? operator’s error chaining. A basic implementation requires only that the type implement Debug and Display:
impl std::error::Error for ConfigError {}The Error trait also provides a source method for error chaining, allowing errors to wrap underlying causes:
impl std::error::Error for ConfigError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None // Or return the underlying cause if wrapping another error }}The anyhow and thiserror crates
The ecosystem has converged on two crates for common error handling patterns. The thiserror crate provides derive macros for creating custom error types with minimal boilerplate:
use thiserror::Error;
#[derive(Error, Debug)]pub enum ConfigError { #[error("configuration file not found: {0}")] FileNotFound(PathBuf),
#[error("parse error at line {line}: {message}")] ParseError { line: usize, message: String },
#[error("invalid value '{value}' for key '{key}'")] InvalidValue { key: String, value: String },
#[error("IO error")] Io(#[from] std::io::Error),}The #[error("...")] attributes generate Display
implementations. The #[from] attribute generates From
implementations for automatic conversion with ?.
The following complete example demonstrates thiserror with error chaining and the source() method for accessing underlying causes:
use std::io;use std::num::ParseIntError;use thiserror::Error;
#[derive(Error, Debug)]pub enum ConfigError { #[error("Configuration file not found: {path}")] FileNotFound { path: String, #[source] source: io::Error, },
#[error("Failed to parse configuration at line {line}")] ParseError { line: usize, #[source] source: ParseIntError, }, #[error("Invalid value '{value}' for setting '{key}'")] InvalidValue { key: String, value: String, },
#[error("Missing required setting: {0}")] MissingRequired(String),
#[error(transparent)] Other(#[from] anyhow::Error),}
fn load_config(path: &str) -> Result<Config, ConfigError> { let contents = std::fs::read_to_string(path) .map_err(|e| ConfigError::FileNotFound { path: path.to_string(), source: e, })?;
let port: u16 = contents .lines() .nth(0) .ok_or(ConfigError::MissingRequired("port".to_string()))? .parse() .map_err(|e| ConfigError::ParseError { line: 1, source: e })?;
Ok(Config { port })}
struct Config { port: u16,}
// Printing full error chainfn main() { match load_config("config.txt") { Ok(config) => println!("Loaded config with port {}", config.port), Err(e) => { eprintln!("Error: {}", e);
// Print source chain using std::error::Error trait let mut source = std::error::Error::source(&e); while let Some(cause) = source { eprintln!("Caused by: {}", cause); source = std::error::Error::source(cause); } } }}The #[source] attribute marks fields that contain the underlying error cause. The standard library’s Error trait provides the source() method for traversing the error chain. This pattern enables both user-friendly error messages and detailed diagnostic information for debugging.
The anyhow crate takes a different approach, providing a single error type that can hold any error. This is useful in application code where precise error types matter less than context and convenience:
use anyhow::{Context, Result};
fn load_config(path: &str) -> Result<Config> { let contents = std::fs::read_to_string(path) .context("Failed to read configuration file")?; let config = parse_config(&contents) .context("Failed to parse configuration")?; Ok(config)}The context method adds descriptive messages that appear in error reports. The Result type alias hides anyhow::Error as the error type. This trades precise error handling for convenience and rich error messages.
Library code typically uses thiserror to define precise error types that callers can match on. Application code often uses anyhow to simplify error handling and produce helpful diagnostics. The two approaches complement each other.
When to panic (and when not to)
Panic is Rust’s mechanism for unrecoverable errors. When a panic occurs, the current thread begins unwinding its stack, dropping values and running destructors. If the panic reaches the thread boundary without being caught, the thread terminates. Panics in the main thread terminate the program.
Panics are appropriate when continuing execution would be incorrect or dangerous. Indexing a slice out of bounds panics because returning garbage data would violate memory safety. Division by zero panics in debug builds because the result is undefined. These are not recoverable conditions; they indicate bugs in the program.
The panic! macro triggers a panic explicitly:
fn divide(a: i32, b: i32) -> i32 { if b == 0 { panic!("Division by zero"); } a / b}However, this example illustrates poor panic usage. Division by zero is usually a condition that callers might anticipate and handle. Returning a Result is more appropriate:
fn divide(a: i32, b: i32) -> Result<i32, DivisionError> { if b == 0 { return Err(DivisionError::DivisionByZero); } Ok(a / b)}The distinction is between bug and expected failure. A bug is a programming error that should not happen if the code is correct. An expected failure is a condition that might occur during normal operation due to input, environment, or external systems.
Panics are appropriate for:
- Invariant violations that indicate bugs (internal assertions)
- Unrecoverable conditions that make further execution meaningless
- Situations where the function’s contract has been violated by the caller
- Prototype code where proper error handling is deferred
Results are appropriate for:
- Operations that can fail due to external factors (IO, network, user input)
- Conditions that callers might reasonably want to handle
- Library code where callers should decide how to respond to failure
- Any situation where recovery is possible and sensible
Why panics are not exceptions
Developers familiar with C++, Java, or C# might observe that Rust panics involve stack unwinding just like exceptions do, and wonder why Rust claims to avoid exception-based error handling. The mechanical similarity obscures a fundamental philosophical difference in how these mechanisms are intended to be used.
Exceptions in traditional object-oriented languages serve as the primary error handling mechanism. A method throws an exception when it cannot fulfill its contract, and callers are expected to catch and handle that exception somewhere up the call stack. Exception handling is part of normal control flow. Java’s try-catch blocks, C#‘s exception filters, and C++‘s catch hierarchies are all designed around the assumption that exceptions represent recoverable conditions that programs routinely handle.
Panics serve a categorically different purpose. A panic indicates a bug or an unrecoverable condition where continuing execution would be incorrect. Programs are not expected to catch panics as part of normal operation. When a panic occurs, the appropriate response is usually to let it propagate, terminate the thread or program, and fix the underlying bug. The unwinding mechanism exists primarily to ensure destructors run and resources are cleaned up during this termination, not to enable recovery.
This philosophical difference manifests in several concrete ways. First, Rust provides no built-in syntax for catching panics. Where Java has try-catch and C++ has try-catch, Rust requires the explicit std::panic::catch_unwind function, which is awkward to use by design. The catch_unwind function exists for specific scenarios: FFI boundaries where panics must not cross into C code, thread pools that need to isolate failures, and test harnesses that need to verify panic behavior. It is not intended for routine error handling.
Second, panics can be configured to abort immediately rather than unwind. Setting panic = “abort” in Cargo.toml causes panics to terminate the process without unwinding. Many production deployments use this configuration because unwinding adds code size and runtime cost. Code that relies on catching panics would break under abort mode, reinforcing that panics are not meant to be caught.
Third, and most importantly, Rust’s type system makes recoverable errors explicit through Result. Functions that might fail in expected ways return Result, and the compiler forces callers to handle the error case. This addresses the fundamental problem with exceptions: hidden control flow. In exception-based languages, any function call might throw, and determining which functions throw which exceptions requires reading documentation (if it exists) or source code. In Rust, the function signature declares whether and how it can fail. Functions that do not return Result do not have recoverable failure modes that callers must handle.
The combination of Result for recoverable errors and panic for bugs creates a clear separation. When you call a function returning Result, you know it might fail and must decide how to handle that failure. When you call a function not returning Result, you know it will either succeed or panic due to a bug, not due to an expected failure condition. This clarity is what Rust means by “error handling without exceptions,” even though the panic mechanism shares some implementation characteristics with exceptions.
Consider what happens when a library uses exceptions versus panics incorrectly. A Java library that throws exceptions for unexpected conditions forces callers to write catch blocks for errors that should never occur. A Rust library that panics for expected failures forces callers to use catch_unwind, which is cumbersome and fails under abort mode. Both are poor API design, but Rust’s conventions and type system make the correct choice obvious: return Result for expected failures, panic only for bugs.
Assertions and Debug checks
The assert! macro panics if its condition is false:
fn process(data: &[u8]) { assert!(!data.is_empty(), "Data must not be empty"); // proceed knowing data has at least one element}Assertions document invariants and catch bugs early. They run in both debug and release builds by default.
The debug_assert! macro runs only in debug builds, disappearing entirely in release builds:
fn expensive_check(data: &[u8]) { debug_assert!(is_valid(data), "Data validation failed"); // is_valid might be slow; skip in release builds}Use debug_assert for invariants that are expensive to check or that should never fail once the code is tested.
The unreachable! macro marks code paths that should never execute:
fn handle_variant(value: MyEnum) -> i32 { match value { MyEnum::A => 1, MyEnum::B => 2, _ => unreachable!("All variants handled"), }}If execution reaches unreachable!, the program panics. This catches bugs where assumptions about possible values are incorrect.
Error handling patterns in practice
Effective error handling combines these tools appropriately. Functions performing multiple fallible operations use ? to propagate errors concisely. Custom error types provide context and enable structured handling. Panics guard against bugs but do not replace Result for expected failures.
Consider a function that downloads data, parses it, and stores results:
pub fn sync_data(url: &str, db: &Database) -> Result<SyncResult, SyncError> { let response = fetch(url)?; if response.status != 200 { return Err(SyncError::HttpError(response.status)); } let data: Vec<Record> = parse_json(&response.body)?; let mut stored = 0; for record in data { match db.store(&record) { Ok(_) => stored += 1, Err(e) if e.is_duplicate() => continue, Err(e) => return Err(SyncError::Database(e)), } } Ok(SyncResult { fetched: data.len(), stored })}This function uses ? for straightforward propagation, explicit matching where partial failure is acceptable (duplicate records), and early return for unrecoverable conditions. The error type SyncError unifies errors from HTTP, parsing, and database operations.
Error handling in Rust is verbose compared to exception-based languages. This verbosity is intentional. It makes error paths visible in the code, ensures they are considered, and produces programs where failure modes are explicit rather than hidden. The initial investment in handling errors properly pays dividends in reliability and maintainability.
Key Lessons
Result is Rust’s primary mechanism for recoverable errors, replacing exceptions with explicit values that callers must handle. The Ok variant contains success values; the Err variant contains error information. Functions that can fail declare this in their return type, making error handling part of the API contract.
The ? operator propagates errors concisely, extracting Ok values or returning Err early. It relies on From trait implementations to convert between error types, enabling unified error handling across operations with different error types.
Custom error types provide domain-specific context and enable structured error handling. The thiserror crate reduces boilerplate for error type definitions. The anyhow crate simplifies error handling in application code where precise types matter less than convenience.
Panics handle unrecoverable errors and bugs. They terminate execution by unwinding the stack. Use Result for expected failures where callers might recover; use panic for bugs and violated invariants.
The next chapter explores collections and iterators, examining how Rust’s standard library provides efficient data structures and the iterator pattern that makes working with sequences both expressive and performant.