std::panic provides tools for changing what happens when a Rust program panics. A panic is an orderly failure: the program reports a problem and unwinds the thread's stack to clean up memory. section 21.2
The module supports several practical panic-handling tasks:
- Use set_hook() to replace the default panic output with a closure that prints custom messages or formats panic information. section 21.2
- Read PanicInfo data such as the panic payload, message, source location, and whether unwinding is possible. section 21.2
- Use take_hook() to remove the current custom hook and recover the previous hook, unless the calling thread is already panicking. section 21.2
A custom panic message
Install a hook with std::panic::set_hook(Box::new(|_| { println!("Oops, that didn't work."); })); and then call panic!(). The custom message replaces the usual default panic report.
