The Analogy: The Emergency Stop Button
Every production line has a big red mushroom button, and everybody on the floor knows two things about it. It stops the line immediately -- not gracefully, not after finishing the current unit, just stopped. And it is the correct response to exactly one category of event: something has gone wrong that the line has no procedure for. A hand in the machine. A guard rail found unlatched. The line has an orderly way to handle running out of blue caps -- an alarm, a refill, resume -- and it has no orderly way at all to handle a hand in the machine.
Pressing it does not freeze everything mid-motion, though. There is a shutdown sequence: clamps release, the conveyor brakes, the safety guards drop into place. Things get put down properly on the way out. There is also a hard option -- pull the main breaker -- which is faster and leaves the machine in whatever state it happened to be in, with parts still clamped and guards still up. Rust has both: a panic normally unwinds, running every value's cleanup on the way down, and can instead be configured to abort, which cuts the power.
Whoever presses the button writes an incident report: what they saw, where they were standing, when. Without it the next shift arrives to a stopped line and no idea why, which is worse than the fault itself. A panic's message and location are that report, and the backtrace is the full statement -- who called whom, all the way down to the button.
Finally, the thing that ruins e-stops in real factories: pressing them for the wrong reasons. A line where somebody hits the button every time the caps run low is a line where the button has stopped meaning anything, and where an operator will hesitate the one time it matters. Code has the same failure mode. A library that panics because a user typed a letter into a number field has taken a decision that belonged to its caller, and has spent the strongest signal it owns on the weakest situation it will ever see.
Syntax or Core Structure
panic! takes a format string exactly like println!, prints it with a location, and ends the thread.
fn main() {
let stock = 3;
let wanted = 10;
println!("checking {wanted} against {stock}");
if wanted > stock {
panic!("cannot ship {wanted} units, only {stock} in stock");
}
println!("shipped");
}
Output:
checking 10 against 3
thread 'main' panicked at src/main.rs:8:9:
cannot ship 10 units, only 3 in stock
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The println!("shipped") never runs, and neither would anything after the call if this had been a function. The process exits with status 101, which is Rust's dedicated panic code rather than a generic 1 -- so a wrapper script or a supervisor can tell "this program panicked" apart from "this program decided to fail". The message goes to standard error, which matters when you are piping standard output somewhere and wondering why the error vanished.
| Part of the output | What it tells you |
|---|---|
thread 'main' panicked at | which thread died; panics are per-thread, not per-process |
src/main.rs:8:9 | the file, line, and column of the panicking expression |
| the message line | your format string, already filled in |
the RUST_BACKTRACE note | how to get the chain of calls that led here |
Technical Depth: The Panics You Did Not Write
Most panics in real programs contain no panic! anywhere near them. The standard library panics on your behalf whenever an operation has no sensible answer, and learning to recognise those messages is most of the skill.
| Operation | Message |
|---|---|
v[i] past the end | index out of bounds: the len is 3 but the index is 7 |
integer a / 0 | attempt to divide by zero |
integer a % 0 | attempt to calculate the remainder with a divisor of zero |
| arithmetic overflowing, debug build | attempt to add with overflow |
Option::unwrap on None | called Option::unwrap() on a None value |
.expect("msg") on None | msg |
&s[i..j] off a char boundary | byte index j is not a char boundary; it is inside ... |
slice.first().unwrap() on empty | called Option::unwrap() on a None value |
RefCell borrowed twice mutably | already borrowed: BorrowMutError |
Every one of these is a choice the standard library made, and in almost every case there is a non-panicking sibling waiting: get instead of [], checked_div instead of /, get(i..j) instead of &s[i..j], try_borrow_mut instead of borrow_mut. Reaching for the panicking form is a statement that you have already proved the bad case cannot happen.
Integer Overflow Changes Behaviour Between Profiles
This is the one that surprises people, because it is the only place where a debug and a release build of the same source disagree about what the program means.
fn main() {
let mut count: u8 = 250;
for _ in 0..10 {
count += 1;
println!("{count}");
}
}
Output (debug build, cargo run):
251
252
253
254
255
thread 'main' panicked at src/main.rs:5:9:
attempt to add with overflow
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Output (release build, cargo run --release):
251
252
253
254
255
0
1
2
3
4
Neither of these is a bug in Rust. Overflow checks cost a branch on every arithmetic operation, so the default dev profile turns them on and the default release profile turns them off, and both are documented. What is a bug is code that relies on either one. If wrapping is what you want, say so; if overflow is impossible, prove it; if it is possible and matters, handle it.
| Written as | On overflow |
|---|---|
count + 1 | panics in debug, wraps in release |
count.wrapping_add(1) | wraps, in both profiles, always |
count.checked_add(1) | returns Option<u8>, None on overflow |
count.saturating_add(1) | clamps at u8::MAX |
count.overflowing_add(1) | returns (u8, bool) -- the wrapped value and a did-it-overflow flag |
You can also force the checks on in release with overflow-checks = true under [profile.release] in Cargo.toml, which is a reasonable thing to do for a service where a silent wrap would be worse than a crash.
Unwinding: What Happens On The Way Down
A panic does not simply stop. It walks back up the call stack, and as it leaves each scope it runs the cleanup for every value that scope owned. The easiest way to see it is to give a type a visible farewell.
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
fn inner() {
let _b = Guard("inner");
panic!("something broke");
}
fn main() {
let _a = Guard("outer");
inner();
println!("never reached");
}
Output:
thread 'main' panicked at src/main.rs:11:5:
something broke
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
dropping inner
dropping outer
The report is printed first, by the panic hook, before any unwinding starts. Then the stack comes apart in the reverse of the order it was built: inner's guard goes, then main's. This is why a panic does not leak a file handle or leave a lock permanently held -- the same Drop machinery that runs at the end of a normal scope runs here too. Module 8 covers Drop properly; treat it here as a way to make cleanup audible.
Now put this in Cargo.toml:
[profile.release]
panic = "abort"
Output (cargo run --release):
thread 'main' panicked at src/main.rs:11:5:
something broke
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
The two dropping lines are gone. The process was killed where it stood. Your shell will additionally report the abort itself -- on Unix that is usually a line about the process being aborted, and the exit status becomes the platform's signal status rather than 101.
| unwind (default) | abort | |
|---|---|---|
| Destructors on the way down | run | do not run |
Buffered output flushed by Drop | yes | no |
| Binary size | larger; every scope needs landing pads | smaller |
| Exit status | 101 | the platform's abort status |
catch_unwind can intercept it | yes | no |
| Sensible for | almost every program | tight embedded targets; builds where a panic must be unstoppable |
std::panic::catch_unwind deserves one sentence and no more: it exists so that a runtime embedding Rust can stop a panic from crossing a boundary it must not cross, and it is not an error-handling tool. Using it to "try" a block will get you code that cannot tell a bug from a bad input, cannot resume safely because the data it was working on may be half-updated, and stops working entirely the day somebody sets panic = "abort".
The Panic Family
panic! is the raw form. Most of the time you want one of its relatives, which say why you are stopping as well as that you are.
| Macro | Panics when | Removed in release |
|---|---|---|
panic!("...") | control reaches it | no |
assert!(cond, "...") | cond is false | no |
assert_eq!(a, b) | a != b, and prints both values | no |
assert_ne!(a, b) | a == b | no |
debug_assert!(cond) | cond is false | yes |
unreachable!() | control reaches it, which you proved it cannot | no |
todo!() | reached; means "not written yet" | no |
unimplemented!() | reached; means "will not be written" | no |
todo!() and unimplemented!() also have a useful side effect: they return !, the never type, so they type-check as any value at all. That is what lets you stub out a function body and still compile the code around it.
fn discount(price: u32, percent: u32) -> u32 {
assert!(percent <= 100, "percent must be 0..=100, got {percent}");
price - price * percent / 100
}
fn main() {
println!("{}", discount(2000, 25));
println!("{}", discount(2000, 250));
}
Output:
1500
thread 'main' panicked at src/main.rs:2:5:
percent must be 0..=100, got 250
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Without that assert, the second call computes 2000 - 2000 * 250 / 100, which is 2000 - 5000, which underflows u32 -- and so it would still have panicked in a debug build, with the message "attempt to subtract with overflow" and a location pointing at the arithmetic. Same crash, far worse report. The assert converts an implementation-level accident into a domain-level statement, and it does it one line earlier.
Reading a Backtrace
The location in a panic message is where the button was pressed, not who walked into the room. For that you need the call chain:
RUST_BACKTRACE=1 cargo run
The output is long and machine-specific -- frame numbers, addresses and library paths differ between builds and platforms, so there is no point reproducing one here. What is worth knowing is its shape. The top frames are always panic machinery: the hook, the formatter, the runtime's entry point into unwinding. Below those come the standard library frames for whatever operation panicked. The frame you actually want is the first one that names your own crate, and the frames under it are your callers, innermost first. RUST_BACKTRACE=full adds the frames that were elided as uninteresting, which is occasionally what you need and usually noise.
A release build with the default settings keeps enough symbol information to be readable, but inlining will have merged small functions, so a frame you expected may simply not exist. Setting debug = true under [profile.release] gets line numbers back at the cost of a much larger binary.
The Rule For Deciding
There is one test, and it is not "how bad is this outcome".
Could a correct caller, doing everything right, still end up here?
If yes, it is not a panic. A missing file, a number that will not parse, a closed socket, a user typing nonsense -- these are all things the world does to a correct program, and a correct program is entitled to be told about them in a value it can inspect. That value is Result, and it is the subject of the next lesson.
If no, panic. An index you computed yourself that came out past the end, a state machine in a state you documented as impossible, an invariant your own module promised to maintain and did not -- these mean the code is wrong. There is no argument the caller can make that fixes it, and continuing means operating on data you have just proved you do not understand.
Two corollaries follow from that, and they pull in opposite directions depending on where you sit.
- In a library, panicking on caller input is close to a bug. You have converted their recoverable situation into your crash, in their process, on their production traffic. The exceptions are narrow and conventional: indexing operators, and functions documented as panicking with a
# Panicssection. - In
main, a panic is a legitimate last resort. There is nobody above you to inform. A binary that discovers its config file is malformed at startup and panics has behaved reasonably; the alternative is printing a message and callingstd::process::exit(1), which differs mainly in being quieter and skipping the backtrace.
Panics in tests are a special case worth knowing early: a test that panics is a test that failed, which is exactly how assert_eq! reports a wrong answer. And a test can require a panic with #[should_panic(expected = "...")], which is how you check that your own guard rails work. Module 7 covers testing properly.
Real World Example: A Seat Allocator That Fails Fast
A hall of seats is a good place to see both mechanisms side by side, because it has two genuinely different kinds of failure: the show can be sold out, and the caller can ask about a row that does not exist. Only one of those is a bug.
struct Hall {
rows: usize,
per_row: usize,
taken: Vec<bool>,
}
impl Hall {
fn new(rows: usize, per_row: usize) -> Hall {
assert!(rows > 0, "a hall needs at least one row");
assert!(per_row > 0, "a row needs at least one seat");
assert!(
rows * per_row <= 10_000,
"hall of {rows}x{per_row} exceeds the 10000 seat limit"
);
Hall {
rows,
per_row,
taken: vec![false; rows * per_row],
}
}
fn index_of(&self, row: usize, seat: usize) -> usize {
assert!(row < self.rows, "row {row} does not exist in {} rows", self.rows);
assert!(seat < self.per_row, "seat {seat} does not exist in rows of {}", self.per_row);
row * self.per_row + seat
}
fn reserve(&mut self, row: usize, seat: usize) -> bool {
let i = self.index_of(row, seat);
if self.taken[i] {
false
} else {
self.taken[i] = true;
true
}
}
fn next_free(&self) -> Option<(usize, usize)> {
for row in 0..self.rows {
for seat in 0..self.per_row {
if !self.taken[self.index_of(row, seat)] {
return Some((row, seat));
}
}
}
None
}
fn free_count(&self) -> usize {
let mut n = 0;
for &t in &self.taken {
if !t {
n += 1;
}
}
n
}
}
And the driver, continuing the same file:
fn main() {
let mut hall = Hall::new(2, 3);
println!("{} seats, {} free", hall.rows * hall.per_row, hall.free_count());
println!("reserve (0,0) -> {}", hall.reserve(0, 0));
println!("reserve (0,0) -> {}", hall.reserve(0, 0));
println!("reserve (0,1) -> {}", hall.reserve(0, 1));
println!("next free -> {:?}", hall.next_free());
while let Some((row, seat)) = hall.next_free() {
hall.reserve(row, seat);
}
println!("next free -> {:?}", hall.next_free());
println!("{} free", hall.free_count());
println!("asking for row 9");
hall.reserve(9, 0);
}
Output:
6 seats, 6 free
reserve (0,0) -> true
reserve (0,0) -> false
reserve (0,1) -> true
next free -> Some((0, 2))
next free -> None
0 free
asking for row 9
thread 'main' panicked at src/main.rs:24:9:
row 9 does not exist in 2 rows
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Two kinds of failure, two different mechanisms, and the split is not about severity. "The hall is full" comes back as None from next_free, because a sold-out show is a normal Tuesday and every caller has an obvious thing to do about it. "Row 9 of a two-row hall" panics, because no correct caller can produce that number: the row indices either came out of next_free, which only ever emits rows that exist, or out of a booking system that was told the hall's shape. A caller who passes 9 has a bug somewhere upstream, and the most useful thing this code can do is stop close to it.
The asserts in new are startup validation. They run once, they cost nothing measurable, and the failure they catch -- a hall configured with zero rows -- would otherwise show up much later as a mysteriously empty taken vector. The asserts in index_of are a different bargain: they run on every single seat operation, and they are redundant, because self.taken[i] would panic on an out-of-range index anyway. What they buy is the message. "row 9 does not exist in 2 rows" names the domain; "index out of bounds: the len is 6 but the index is 27" names the implementation and leaves the reader to reverse-engineer row * per_row + seat to find out what was actually asked for.
reserve returns bool rather than panicking on a double booking, which is the same judgement call again -- two people clicking the same seat is expected behaviour, not a bug. But bool is a poor return type here for a reason that has nothing to do with panicking: it cannot say why it refused. A caller receiving false cannot distinguish "already taken" from any other reason a future version of this method might decline, and cannot show a useful message. That gap is exactly what Result is for, and the next lesson fills it.
The honest limits. Those index_of asserts stay compiled into release builds, which is the right default for a bounds check on a public method and the wrong default for something in a hot inner loop -- next_free calls index_of once per seat, so a real 6,000-seat hall pays for 6,000 redundant comparisons per scan. free_count walks the whole vector rather than keeping a running counter, which is fine at this size and would not be inside a request handler. The 10,000-seat cap is an arbitrary number defending against nothing more specific than a typo, and it belongs in a named constant with a comment saying so. And while a panic at startup for an invalid layout is a genuinely good outcome, a panic in index_of in production is a crashed request; the real fix is not a better message but a Row type that cannot hold 9 in the first place, so the check happens once at the edge instead of on every call.
Common Mistakes
- Panicking on caller input inside a library. A parser that panics on malformed text has decided, on your users' behalf, that malformed text is a bug in their program. It is not; it is Tuesday. Return a value that says so.
- Assuming release builds catch integer overflow. They do not, by default. Code that was "safe because it panics on overflow" silently wraps the moment somebody ships it, which is the worst possible time to find out.
- Assuming destructors always run. They do not under
panic = "abort", and they do not if the panic itself happens inside aDropimplementation -- a panic while unwinding aborts the process immediately. Never rely onDropfor something that must happen.
- Using
catch_unwindas atry/catch. It cannot distinguish a bug from a bad input, the data it was working on may be half-updated, and the whole thing stops functioning the day the profile switches to abort.
- Messages that name no values.
panic!("invalid state")tells you the file and line and nothing else.panic!("invalid state {state:?} after {n} steps")tells you what happened. The formatting cost is paid only on the way out.
- Reaching for
debug_assert!when the check must survive. It compiles to nothing in release, so adebug_assert!guarding a genuine safety condition is a check that exists only on your laptop. Use it only for assertions that are expensive and provably implied by ones that do ship.
- Expecting a panicking thread to stop the program. A panic in a spawned thread kills that thread.
maincarries on, none the wiser, until it joins that handle and inspects the result -- and code that never joins never finds out at all. Module 8 covers threads.
- Expecting exit code 1. A Rust panic exits with 101. Scripts that check for
1will read a panic as success-adjacent, or at least as something other than what it was.
- Leaving
todo!()in shipped code. It compiles, it type-checks as anything, and it passes review because it looks like a note. It is a panic with a cheerful name.
Best Practices
- Apply the one test. Could a correct caller reach this? If yes, return a value. If no, panic. Decide it deliberately for every failure point rather than by whichever is quicker to type.
- Put the values in the message. The location tells you where; only you can tell the reader what. Include the inputs that made the situation impossible.
- Prefer
assert!with a message over a bare bounds check. One extra line converts an implementation-level accident into a domain-level statement, and it fires one step closer to the caller's mistake.
- Choose overflow behaviour explicitly.
checked_,saturating_,wrapping_andoverflowing_all say what you meant. Relying on the profile says nothing, and says it differently in dev and in production.
- Document panics. If a public function can panic, say so in a
# Panicssection of its doc comment. Callers audit those; they cannot audit your reasoning.
- Know what your production logs capture. A panic message on stderr is worthless if nothing is reading stderr. Decide, before you need it, whether backtraces are enabled in the environment where you will actually be debugging.
- Treat
panic = "abort"as a deliberate decision. It buys a smaller binary and costs you every destructor. That is a fine trade on an embedded target and a poor one for a service that flushes logs on shutdown.
- Never let a panic cross an FFI boundary. Unwinding into non-Rust frames is undefined behaviour. If you export a function to C, catch the unwind at the boundary or compile with abort.
Practice Exercises
- Sharpen a message. Take the
Hallprogram, delete both asserts fromindex_of, and runhall.reserve(9, 0)again. Record the message you get instead, then work out by hand what row and seat produced that index. Put the asserts back and write two sentences on what the difference is worth.
- Overflow, five ways. Write the
u8counter loop and run it in both profiles, recording both outputs. Then rewrite the increment four more times usingchecked_add,wrapping_add,saturating_addandoverflowing_add, and for each one describe in a sentence what the loop now does when it reaches 255.
- Watch the unwind stop. Add the
Guardtype to theHallprogram, hold one inmainand one inside a helper that panics. Run it, then addpanic = "abort"under[profile.release]and runcargo run --release. Report which lines disappeared and what the exit status became.
- Reclassify every failure. List all six places the
Hallprogram can fail: the three asserts innew, the two inindex_of, andreservereturningfalse. For each, apply the correct-caller test and argue whether it should stay a panic, become a returned value onceResultis available, or be made impossible by a better type.