liveBook · Manning

Panic

As explained in Write Powerful Rust Macros

A panic is Rust's unrecoverable failure mechanism that stops ordinary execution and may unwind the stack to clean up resources.

A panic stops ordinary Rust execution when something happens that should be impossible or makes continued operation unsafe. Unlike Result, which turns failure into a value, panic stops the program and may unwind the stack to clean up resources. section 7.4

Use panic for exceptional conditions rather than ordinary, expected failures:

  • Stop when essential configuration is missing and the application cannot do useful work. section 7.4
  • Reserve panic for states that cannot happen, such as an unwrap after a successful digit check; prefer expect with a diagnostic message. section 7.4
  • Return Result for normal failures such as insufficient funds or unavailable inventory, so callers must acknowledge the error. section 7.4
  • Avoid panics in production procedural macros when syn::Error or proc_macro_error can report useful compiler diagnostics. section 7.12

Cleanup during unwinding

A value implementing Drop is cleaned up when panic unwinds the stack. In the example, some_fun never reaches mem::forget after panic!, so Dropper::drop runs. If panic! is removed, forget prevents Drop from running. section 4.8

struct Dropper {}
impl Drop for Dropper {
    fn drop(&mut self) { #1
        println!("Dropping!")
    }
}              

fn some_fun() {
    let d = Dropper {};
    panic!("panic");      #2
    core::mem::forget(d);     #3
}

fn main() {
    some_fun();
}

Trace the execution order around panic!, Drop, and mem::forget. section 4.8

How Write Powerful Rust Macros covers it

How deep it goes
Explains selection guidelines, worked Rust examples, unwinding cleanup, and procedural-macro implications.
Examples
Uses invalid person validation, checked digit conversion, missing configuration, and Dropper cleanup examples.
What it assumes
Assumes Rust function and enum familiarity while reinforcing Result, unwrap, expect, Drop, and resource cleanup.
What you can do after
Evaluate/understand when to stop execution, preserve cleanup, choose Result, or improve panic diagnostics.
How it connects
Connects panic with Result, error handling, unwrap, expect, Drop, stack unwinding, and procedural macro diagnostics.

Also explained in

Compare how 8 books explain panic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.