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







