expression

Clean up a prefix during panic unwinding

During unwinding, local guards normally run their destructors. This standalone demonstration deliberately panics after initializing one slot and catches that panic to inspect cleanup. It assumes panic=unwind, a nonpanicking destructor and a single-threaded test process; the temporary global hook is restored after the test. Do not use catch_unwind for ordinary recoverable errors. Expected stdout (not executed): caught=true drops=1 Common mistake: Assuming destructors always run when panic=abort or that catch_unwind catches every panic.

Formal Syntax & Structure

rust syntaxrust
Drop guard + catch_unwind

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::{cell::Cell, mem::MaybeUninit, panic};    struct Item<'a>(&'a Cell<u32>);    impl Drop for Item<'_> {        fn drop(&mut self) { self.0.set(self.0.get() + 1); }    }    struct Guard<'a> { slot: MaybeUninit<Item<'a>>, initialized: bool }    impl Drop for Guard<'_> {        fn drop(&mut self) {            if self.initialized {                self.initialized = false;                // SAFETY: flag was set only after a complete write; unique live value.                unsafe { self.slot.assume_init_drop(); }            }        }    }    let count = Cell::new(0);    let old_hook = panic::take_hook();    panic::set_hook(Box::new(|_| {}));    // The captured Cell is only a counter; the guard owns all temporary state.    let result = panic::catch_unwind(panic::AssertUnwindSafe(|| {        let mut guard = Guard { slot: MaybeUninit::uninit(), initialized: false };        guard.slot.write(Item(&count));        guard.initialized = true;        panic!("test failure");    }));    panic::set_hook(old_hook);    println!("caught={} drops={}", result.is_err(), count.get());}
Rust Reference