std-function
catch_unwind — catch an unwinding panic
Run a closure at a panic boundary. On an unwind it returns the panic payload; an aborting panic terminates the process instead. The hook normally runs before the catch, and the recovered state still needs validation. Expected stdout (not executed): caught: true Common mistake: Using it to validate ordinary user input or assuming it catches every failure.
Formal Syntax & Structure
rust syntaxrust
pub fn catch_unwind<F: FnOnce() -> R + UnwindSafe, R>(f: F) -> std::thread::Result<R>Working Example
Example Snippetrust
fn main() { let outcome = std::panic::catch_unwind(|| panic!("demo invariant")); println!("caught: {}", outcome.is_err());}