1 Panics the current thread.
3 This allows a program to terminate immediately and provide feedback
4 to the caller of the program. `panic!` should be used when a program reaches
5 an unrecoverable state.
7 This macro is the perfect way to assert conditions in example code and in
8 tests. `panic!` is closely tied with the `unwrap` method of both
9 [`Option`][ounwrap] and [`Result`][runwrap] enums. Both implementations call
10 `panic!` when they are set to [`None`] or [`Err`] variants.
12 When using `panic!()` you can specify a string payload, that is built using
13 the [`format!`] syntax. That payload is used when injecting the panic into
14 the calling Rust thread, causing the thread to panic entirely.
16 The behavior of the default `std` hook, i.e. the code that runs directly
17 after the panic is invoked, is to print the message payload to
18 `stderr` along with the file/line/column information of the `panic!()`
19 call. You can override the panic hook using [`std::panic::set_hook()`].
20 Inside the hook a panic can be accessed as a `&dyn Any + Send`,
21 which contains either a `&str` or `String` for regular `panic!()` invocations.
22 To panic with a value of another other type, [`panic_any`] can be used.
24 [`Result`] enum is often a better solution for recovering from errors than
25 using the `panic!` macro. This macro should be used to avoid proceeding using
26 incorrect values, such as from external sources. Detailed information about
27 error handling is found in the [book].
29 See also the macro [`compile_error!`], for raising errors during compilation.
31 [ounwrap]: Option::unwrap
32 [runwrap]: Result::unwrap
33 [`std::panic::set_hook()`]: ../std/panic/fn.set_hook.html
34 [`panic_any`]: ../std/panic/fn.panic_any.html
35 [`Box`]: ../std/boxed/struct.Box.html
36 [`Any`]: crate::any::Any
37 [`format!`]: ../std/macro.format.html
38 [book]: ../book/ch09-00-error-handling.html
40 # Current implementation
42 If the main thread panics it will terminate all your threads and end your
43 program with code `101`.
48 # #![allow(unreachable_code)]
50 panic!("this is a terrible mistake!");
51 panic!("this is a {} {message}", "fancy", message = "message");
52 std::panic::panic_any(4); // panic with the value of 4 to be collected elsewhere