Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 132 ยท Error Handling

Panics

Learn how Rust panics work - panic!, unwrap and expect, index out of bounds, integer overflow, unwinding versus abort, RUST_BACKTRACE, catch_unwind and when a panic is the right choice.

Rust splits errors into two families. Recoverable errors, like a file that does not exist or text that is not a number, are values you handle with Result. Unrecoverable errors are bugs: the program reached a state that should be impossible, and continuing would be wrong or dangerous. For those, Rust panics.

A panic stops the current thread, prints a message saying where and why, and by default cleans up on the way out. It is Rust's equivalent of an uncaught exception in other languages, but you are not supposed to use it for ordinary control flow. This lesson shows how panics are triggered, how to read the message, what happens to your data while the stack unwinds, and how to decide between panicking and returning a Result.

Your first panic

The panic! macro takes a format string just like println!. The program stops and the process exits with code 101.

Rust A deliberate panic (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The output is before on standard output, and on standard error a message like thread 'main' (2) panicked at main.rs:3:5: followed by something went badly wrong: code 42 and a note about RUST_BACKTRACE. The location main.rs:3:5 is the file, line and column of the panic! call, which is the first thing to read when debugging. The runner also shows exit code 101, the code Rust uses for a panicking main.

Where panics come from

You rarely write panic! yourself. Most panics come from standard operations that have a precondition. Here is a field guide.

Cause Example Message starts with
Out-of-bounds index v[10] on a 3-element Vec index out of bounds
unwrap on None / Err None::<i32>.unwrap() called `Option::unwrap()` on a `None` value
expect parse().expect("number") your message, then the error
Integer overflow (debug) 255u8 + 1 attempt to add with overflow
Division by zero 10 / zero attempt to divide by zero
Failed assertion assert_eq!(1, 2) assertion `left == right` failed
RefCell double borrow two borrow_mut() already borrowed
Slicing off a UTF-8 boundary &"รฉ"[0..1] byte index 1 is not a char boundary
unreachable!, todo!, unimplemented! placeholder code not yet implemented etc.

Let us trigger several of them safely. The next example catches each panic with std::panic::catch_unwind purely so we can show all of them in one run; normal programs do not do this.

Rust Common panics, one after another

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each failing closure reports panicked, and the last one reports ok. (The 3 printed by the last closure also appears in the output.) Because we compile with debug assertions and overflow checks, x + 1 on 255u8 panics; in a release build it would silently wrap to 0 unless you use checked_add, wrapping_add or saturating_add. See overflow.

Reading the real message

Let us look at what an unhandled panic prints for the most common bug, a bad index.

Rust Index out of bounds (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The message is index out of bounds: the len is 3 but the index is 3, located at the line of scores[position]. Valid indices are 0 to 2. The fix is to use scores.get(position), which returns an Option and lets you handle the missing case, or to check the length first.

unwrap and expect

Option::unwrap and Result::unwrap return the inner value or panic. expect does the same with your own message, which makes the panic far easier to diagnose:

Rust unwrap versus expect (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first line prints port 8080. The second expect panics with could not read settings file: Os { code: 2, kind: NotFound, message: "No such file or directory" }, so you see both your context and the underlying error. When you decide to use these, treat them as an assertion that "this cannot fail here", and say why in the expect text (for example expect("regex literal is valid")).

Prefer expect("why this cannot fail") over a bare unwrap() in anything beyond a quick experiment. In tests and tiny examples unwrap is perfectly fine.

What happens during a panic: unwinding

By default a panic unwinds the stack. Rust walks back up through the active function calls and runs the destructors (Drop) of every value still alive, so files are closed, locks are released and memory is freed. Then the thread ends. If it was the main thread, the process exits with code 101.

Rust Drop runs while unwinding (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

You see inner is about to fail, then the panic message on standard error, and the lines cleaning up inner followed by cleaning up main on standard output, in reverse order of creation. That cleanup is what makes unwinding safe, and it is one reason a panic in one thread need not corrupt the rest of the program.

Unwinding has costs: extra code in your binary and some optimisation barriers. You can switch to abort mode in Cargo.toml:

TOML
# Cargo.toml (read-only: this runner has no Cargo)
[profile.release]
panic = "abort"

With panic = "abort", a panic prints its message and immediately terminates the process with no unwinding and no destructors. The binary is smaller and slightly faster, but catch_unwind no longer works and cleanup code is skipped. Use it for servers that restart on failure, embedded targets and small CLI tools; avoid it when destructors must run.

RUST_BACKTRACE

When a panic comes from deep inside your code, you want to know the chain of calls that led there. Set the environment variable RUST_BACKTRACE=1 (or full for even more detail) before running a program and Rust prints a backtrace after the message:

Terminal
# read-only: shell commands
RUST_BACKTRACE=1 cargo run
RUST_BACKTRACE=full ./target/debug/myprogram

On Windows PowerShell the syntax is $env:RUST_BACKTRACE = 1. The panic message even reminds you: note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace. Backtraces work best in debug builds, where function names and line numbers are available. Look for the first frame that belongs to your crate; frames above it are standard library internals.

Panics in threads

A panic only kills the thread it happens in. Other threads keep running, and the parent can discover the failure through join, which returns Err if the thread panicked.

Rust A panic in a spawned thread

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The standard panic message for the worker still appears on standard error; join then returns Err, so main can report it and continue. If a thread panics while holding a Mutex, the mutex becomes poisoned, and later lock() calls return an Err. See Mutex.

catch_unwind (rarely)

std::panic::catch_unwind runs a closure and turns a panic into an Err. Rust's documentation is clear that this is not the intended error handling mechanism. Legitimate uses are narrow: a thread-pool or web server stopping one failed job from killing the worker, a test harness, or stopping a panic from crossing an FFI boundary into C code (undefined behaviour). Closures must be UnwindSafe, a marker that warns about broken invariants left behind by a panic.

Rust catch_unwind to isolate a failing job

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The default hook still prints a message to standard error for job 3 before the code above reports it. You can replace the hook with panic::set_hook to log differently. Remember that with panic = "abort", none of this works.

When is a panic the right choice?

A short decision guide:

  • Panic when a bug in the program has been detected: a violated invariant, an unreachable!() branch, an impossible state, a precondition that the caller promised and broke (like slice indexing). Also in tests, prototypes and examples, where unwrap keeps the code short.
  • Return Result when the failure can happen in a correct program because of the outside world: missing files, bad user input, network errors, parse failures. Callers can decide what to do. See Result and Recoverable Errors.
  • Return Option when absence is normal and carries no error information, such as get on a map.
  • Libraries should almost never panic on bad input; they should return errors and let the application decide. Document any remaining panics in a # Panics section of the doc comment (see comments and docs).

A good habit is to offer both flavours when it is natural: slice[i] panics, slice.get(i) returns an Option; a + b panics on overflow in debug builds, a.checked_add(b) returns an Option.

Writing asserts

Rust offers assertion macros that panic with helpful output when an invariant is broken: assert!(cond), assert_eq!(left, right), assert_ne!, and their debug_assert! versions that are compiled out in release builds. unreachable!() marks code that should never run, and todo!() or unimplemented!() stand in for code you have not written.

Rust Assertions with messages (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The first line prints 5. The second assertion passes silently. The last call panics with average of an empty list is undefined. Failing assert_eq! calls print both the left and right values, which makes test failures easy to read.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which situation is the best fit for a panic?

    Panics signal bugs. Expected failures from the outside world (bad input, missing files, network errors) should be returned as Result values.
  2. 2. What exit code does a Rust program that panics in main use by default?

    An unwound panic in the main thread ends the process with exit code 101.
  3. 3. What happens to local variables with Drop implementations when a panic unwinds the stack?

    Unwinding runs destructors, so resources are released. With panic = "abort" the process terminates immediately and destructors do not run.
  4. 4. What is the advantage of expect("message") over unwrap()?

    Both panic on None or Err. expect adds your own text, which makes the failure much easier to understand.
  5. 5. A spawned thread panics. What does handle.join() return?

    A panic only terminates its own thread. join reports it as an Err so the parent can decide what to do.

Summary

  • A panic means an unrecoverable bug: the thread stops, a message with file, line and column is printed, and the process exits with code 101 when main panics.
  • Common causes: out-of-bounds indexing, unwrap/expect on None or Err, integer overflow in debug builds, division by zero, failed assertions, RefCell double borrows and bad string slicing.
  • Prefer expect("reason") to unwrap(); prefer get, checked_add and Result when failure is expected.
  • Unwinding runs Drop destructors; panic = "abort" skips them and makes binaries smaller.
  • Set RUST_BACKTRACE=1 to see the call chain.
  • A panic only kills its own thread; join returns Err. catch_unwind exists for isolation boundaries, not for normal error handling.
  • Panic for bugs, return Result for expected failures, and have libraries return errors instead of panicking.

Next: Result and Recoverable Errors