Panicking
In the standard library panicking has a defined behavior: it unwinds the stack of the panicking thread, unless the user opted for aborting the program on panics.
In programs without standard library, however, the panicking behavior is left undefined. A behavior can be chosen by declaring a function. This function must appear exactly once in the dependency graph of a program, and must have the following signature: fn(&PanicInfo) -> !
, where is a struct containing information about the location of the panic.
- panic-halt. A panic causes the program, or the current thread, to halt by entering an infinite loop.
- . The panicking message is logged to the host using the semihosting technique.
You may be able to find even more crates searching for the panic-handler keyword on crates.io.
A program can pick one of these behaviors simply by linking to the corresponding crate. The fact that the panicking behavior is expressed in the source of an application as a single line of code is not only useful as documentation but can also be used to change the panicking behavior according to the compilation profile. For example:
Here’s an example that tries to index an array beyond its length. The operation results in a panic.
You can try changing the behavior to panic-halt
and confirm that no message is printed in that case.