Rust Reference ยท Standard Library Modules
The std::panic module
Reference for Rust std::panic: catch_unwind, resume_unwind, panic_any, set_hook, take_hook, PanicHookInfo, Location and UnwindSafe, with examples.
A panic is Rust's way of reporting a bug it cannot recover from locally: an out-of-bounds index, a failed unwrap, an overflow in a debug build, an explicit panic!. By default a panic prints a message, then unwinds the stack, running destructors, until the thread ends. std::panic lets you observe and control that process: change the message with a hook, stop the unwinding with catch_unwind, or start a panic with an arbitrary payload.
Panics are not exceptions for ordinary control flow. Use Result for errors you expect. Catching panics is for boundaries: a thread pool that must survive a bad job, or FFI code that must never let an unwind cross into C.
use std::panic; let result = panic::catch_unwind(|| { let v: Vec<i32> = Vec::new(); v[0] }); assert!(result.is_err());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
| Item | Description |
|---|---|
catch_unwind(f) -> Result<R, Box<dyn Any + Send>> |
Runs f (FnOnce() -> R + UnwindSafe); returns the payload if it panicked. |
AssertUnwindSafe(x) |
Wrapper that tells the compiler you vouch for the closure's unwind safety. |
resume_unwind(payload) |
Continues unwinding with an existing payload, without calling the panic hook. |
panic_any(value) |
Panics with any Any + Send payload. |
set_hook(Box<dyn Fn(&PanicHookInfo)>) |
Replaces the global hook. take_hook() removes it and returns the previous one. |
PanicHookInfo |
Given to the hook: payload(), location(), payload_as_str() (newer compilers). Called PanicInfo before 1.81. |
Location |
file(), line(), column(); Location::caller() with #[track_caller]. |
UnwindSafe, RefUnwindSafe |
Auto traits: values that stay consistent if a panic passes through them. |
Usage notes
panic!("literal")has a&strpayload;panic!("x {}", y)has aString. Check both withdowncast_refas above.- Not every panic can be caught. With
panic = "abort"in the profile, a panic aborts the process andcatch_unwindis useless. A double panic (a panic while unwinding) also aborts. - The hook still runs before unwinding starts, even when you catch the panic; the default hook prints a message to stderr.
RUST_BACKTRACE=1adds a backtrace. - Hooks are process-global. Set one early in
main, and avoid replacing it from library code or in parallel tests. UnwindSafeis advisory, not a safety guarantee. It warns about types like&mut TandRefCellthat might be left half-updated;Mutexpoisons itself for the same reason.- Never unwind across FFI. Use
catch_unwindinsideextern "C"functions and return an error code instead. #[track_caller]makes the location of a panic point at the caller rather than at your helper, asunwrapand indexing do.- Prefer
Resultfor recoverable situations; a library that panics on bad input forces callers to usecatch_unwind. - Threads: a panic only ends the thread it occurs in;
join()returns the payload asErr.
Related
Option::unwrap,Result::unwrap,std::thread,std::error- Lessons: Panic, Threads, FFI