Error Handling at the Machine Level
Rust splits errors into two camps: Result<T, E> for the recoverable kind and panic! for "this should never happen, get out." That model parts ways with both C++ exceptions and C return codes. This lesson breaks down how Result, the ? operator, and panics actually compile, and stacks each one against the alternatives.
Result<T, E> Memory Layout
Result<T, E> is an enum with two variants:
enum Result<T, E> { Ok(T), Err(E),}The memory layout depends on the sizes of T and E:
For Result<i32, i32>:
; Returning Ok(42): xor eax, eax ; Tag = 0 (Ok) mov edx, 42 ; Value = 42 ; Returned in rax:rdx pair
; Returning Err(-1): mov eax, 1 ; Tag = 1 (Err) mov edx, -1 ; Error valueLayout diagrams like the one above go stale as the compiler gets cleverer. The sizes in the diagram come from rustc 1.97 on 64-bit targets: it fits Result<String, io::Error> in 24 bytes by hiding the tag in a niche, and Result<(), io::Error> in 8, because io::Error itself has shrunk to a single word. Older compilers, including the Rust 1.40 in the runner, need 32 bytes for the first one. Run it and see which compiler you're talking to.
The ? Operator in Assembly
The ? operator is Rust's shorthand for "propagate the error or bind the value":
fn read_config(path: &str) -> Result<Config, Error> { let content = std::fs::read_to_string(path)?; let config = parse_config(&content)?; Ok(config)}Each ? compiles to a tag check and conditional branch. Where the tag lives depends on the size of the Result. A 24-byte Result<String, io::Error> is too big for registers, so the caller passes a pointer to a stack slot and the callee writes the result there. A 16-byte result such as Result<Config, io::Error> (with Config a single usize) comes back in rax:rdx. Simplified from rustc 1.97 output at opt-level=2:
read_config: ; read_to_string writes its 24-byte Result into [rsp+8] lea rdi, [rsp+8] ; hidden pointer to the result slot call std::fs::read_to_string mov r15, QWORD PTR [rsp+8] ; String capacity word, doubles as the tag mov rbx, QWORD PTR [rsp+16] cmp r15, <niche value> ; Err stored as an impossible capacity? je .propagate_error_1 ; If so, propagate the error
; Ok: the String is (r15, rbx, [rsp+24]) call parse_config ; small Result: tag in rax, payload in rdx cmp rax, 1 ; Tag == 1 (Err)? je .propagate_error_2
; ... free the String, return Ok(config) in rax:rdx ... ret
.propagate_error_1: ; Return the io::Error (possibly after conversion via From) ret
.propagate_error_2: ; Free the String, then return the parse error retEach ? lowers to a compare and a conditional jump, whether the tag sits in a register or in memory. The branch predictor pegs the not-taken (success) path correctly more or less every time, so on the happy path you're paying close to zero cycles on a modern CPU.
Comparing to C++ Exceptions
// C++ version with exceptions:Config read_config(const std::string &path) { std::string content = read_to_string(path); // throws on error Config config = parse_config(content); // throws on error return config;}; C++ exception version - normal path:read_config_cpp: call read_to_string ; No error check needed! call parse_config ; No error check needed! ret ; Just return the resultThe C++ version has zero overhead on the normal path — no checks at all. The catch comes when something actually throws:
| Aspect | Rust ? | C++ exceptions |
|---|---|---|
| Normal path | 2 instructions per ? | 0 instructions |
| Error path | Return immediately | Unwinder walks tables frame by frame (orders of magnitude slower) |
| Binary size | A branch at every call site | Unwind tables and landing pads |
| Predictability | Similar cost for Ok and Err | Cheap when nothing throws, slow when something does |
| Composability | Explicit at every level | Implicit propagation |
Rust pays a sliver on the happy path (one branch the predictor nails) and gets error handling whose cost doesn't change much when errors start happening. C++ exceptions are cheaper when nothing throws and far more expensive when something does. They aren't free when nothing throws either: the unwind tables and landing pads make the binary bigger and take up cache. How big the throw cost is depends on the unwinder, the depth of the stack and whether the tables are already in cache, so measure it on your own system rather than trusting a single number.
Put the error paths side by side and you can see where each one spends its time. Rust's ? keeps the work in ordinary code at every level. A C++ throw and a Rust panic! both hand control to the same table-driven unwinder, which does nothing until something fails and then does a lot:
The left column costs a compare and branch per frame whether or not anything fails. The right column costs nothing until something fails, then pays a table search and a register restore for every frame it crosses.
Comparing to C Error Codes
// C version with error codes:int read_config(const char *path, Config *out) { char *content = NULL; int err = read_to_string(path, &content); if (err) return err; // Manual check + propagate
err = parse_config(content, out); free(content); if (err) return err; // Manual check + propagate
return 0;}; C error code version:read_config_c: call read_to_string test eax, eax ; Check error jnz .error_1 ; Branch if error
call parse_config test eax, eax jnz .error_2
xor eax, eax ; Return success retThe assembly for Rust's ? and C's if (err) return err; is essentially the same. Both check a return value, both branch on error. What separates them is that Rust enforces the check at compile time — a Result you forget to handle is a warning at minimum, often an error. C cheerfully lets you drop a return code on the floor.
panic! and Unwinding
panic! in Rust has two modes: unwinding and aborting.
Unwinding (default):
fn might_panic(x: i32) { if x < 0 { panic!("negative value!"); }}might_panic: test edi, edi js .panic ; Jump if negative (sign flag set) ret
.panic: ; Set up panic payload lea rdi, [rip+.Lpanic_msg] ; "negative value!" lea rsi, [rip+.Lpanic_loc] ; File, line, column info call core::panicking::panic ; Never returns normally ; This function either unwinds the stack (like C++ exceptions) ; or aborts, depending on the panic strategyUnwinding piggybacks on the same DWARF tables C++ exceptions use. It walks the stack frame-by-frame, calling destructors as it goes, until it hits catch_unwind or runs out of stack and kills the thread.
Abort mode (panic = "abort" in Cargo.toml):
might_panic: test edi, edi js .panic ret
.panic: ; Much simpler: just abort the process call core::panicking::panic ; Calls abort() internally ud2 ; Undefined instruction (unreachable)With abort mode, there are no unwind tables and no landing pads. The binary shrinks and "panic cost" becomes "the process is dead." Embedded folks tend to like this option a lot.
Result with No Runtime Cost: Niche Optimisation
For some Result shapes, the compiler erases the tag entirely:
// Result<&T, ()> - same size as Option<&T>fn find_item(data: &[i32], target: i32) -> Result<&i32, ()> { data.iter().find(|&&x| x == target).ok_or(())}&T is never null and () is zero-sized, so the compiler hijacks the null pointer to mean Err(()):
find_item: ; Returns a pointer (non-null = Ok, null = Err) ; ... search loop ... ret ; rax = pointer or nullNo tag, no padding. The Result is the same width as a raw pointer.
Error Conversion with From Trait
When ? has to coerce one error type into another:
fn example() -> Result<(), Box<dyn std::error::Error>> { let n: i32 = "42".parse()?; // ParseIntError -> Box<dyn Error> let f = std::fs::read("file.txt")?; // io::Error -> Box<dyn Error> Ok(())}The From conversion compiles to a function call on the error path:
call str_parse_i32 test eax, eax jne .convert_and_propagate
; ... continue ...
.convert_and_propagate: ; Convert ParseIntError to Box<dyn Error> ; This allocates a Box and creates a trait object call <ParseIntError as Into<Box<dyn Error>>>::into ; Return the boxed error retThe conversion runs only when something fails. The happy path is free even though the return type is the very flexible Box<dyn Error>.
Benchmark: Error Handling Strategies
In a hot loop chewing through millions of items where roughly 1% trip an error, the picture looks something like this. These figures are illustrative, not measurements:
Rust Result + ?: ~50ns per item (branch predicted correctly 99% of the time)C error codes: ~50ns per item (same mechanism, same cost)C++ exceptions: ~45ns per item normally, ~15,000ns when exception thrownNo error handling: ~48ns per item (saves 2ns from removing the branch)On the happy path ? costs one predicted branch per call site. In all but the tightest of loops, that's noise.
Measure it rather than taking a table's word for it. The runner parses the same inputs two ways, once returning a Result through ? and once panicking and catching the panic with catch_unwind, with half the inputs bad. It's compiled without optimisation, so ignore the absolute times; the gap between the two lines is the point, and it shows up every run.
Key Takeaways
-
Result<T, E>is a tagged union. Same shape as any Rust enum: a discriminant tag plus the payload. -
The
?operator is a conditional branch. Two instructions per?: compare the tag, jump if it's an error. Free in practice when the predictor lands the right side. -
Rust error handling has predictable performance. An
Errtravels back through ordinary returns, so there's no table-driven unwind when something fails. The trade is a branch at every call site. -
panic!is for bugs, not errors. Panics either unwind (like C++ exceptions) or abort. They aren't your routine error-handling tool. -
The assembly matches C error codes.
?produces the same machine code as the manualif (err) return err;dance in C, with the bonus that the compiler refuses to let you forget the check.